How to change the value of Value in a Dictionary [duplicate] - c#

This question already has answers here:
How to update the value stored in Dictionary in C#?
(10 answers)
Closed 2 years ago.
I have a Dictionary<string, int> ad I'd like to amend the int.
I am unable to do so as it's read only.
My effort is
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var itemInList = new Dictionary<string, int>();
itemInList.Add("a", 0);
var existing = itemInList.SingleOrDefault(a => a.Key == "a");
existing.Value++; //fails
}
}
I don't understand what I need to do to fix this

You can use the indexer, like this:
itemInList["a"]++;
That will use the "get" part of the indexer, increment the result, then use the "set" part of the indexer afterwards - so it's equivalent to:
itemInList["a"] = itemInList["a"] + 1;

you are handling the dictionary in wrong way to set a value change your code like this:
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var itemInList = new Dictionary<string, int>();
itemInList.Add("a", 0);
itemInList["a"]+=1; //since dictionaries works on keys identifier
//or
++itemInList["a"];
}
}

Related

Do multidimensional arrays have to be of the same type? [duplicate]

I want to create two dimension array of different type like I can add to that array two values one of them is controlname and second is boolean value.
You can't do that. Instead, you should create a class that contains these two properties, then you can create an array of that type:
public class MyClass
{
public string ControlName {get;set;}
public bool MyBooleanValue {get;set;}
}
public MyClass[] myValues=new MyClass[numberOfItems];
Or, as Anders says, use a dictionary if one of the properties is meant to be used to perform lookups.
A dictionary will work for what you are trying to do then.
Dictionary<string, bool> controllerDictionary = new Dictionary<string, bool>();
To set a value
if (controllerDictionary.ContainsKey(controllerName))
controllerDictionary[controllerName] = newValue;
else
controllerDictionary.Add(controllerName, newValue);
To get a value
if (controllerDictionary.ContainsKey(controllerName))
return controllerDictionary[controllerName];
else
//return default or throw exception
You can't to that with an array.
Perhaps you should be using a Dictionary?
A generic dictionary of Dictionary<string,bool> appears to be the kind of thing that will work for your description.
It depends on how you want to use your array. Do you want to look up the value by a key, or by its index? Konamiman suggested a class. But a class with two types is nothing more than a Dictionary<type of key, type of value>.
You can use a dictionary if you want to obtain the value by a key.
Like so:
Dictionary<string, int> MyDict = new Dictionary<string, int>();
MyDict.Add("Brutus", 16);
MyDict.Add("Angelina", 22);
int AgeOfAngelina = MyDict["Angelina"];
Now the disadvantage of a dictionary is that, you can't iterate over it. The order is undetermined. You can not use MyDict[0].Value to obtain the age of Brutus (which is 16).
You could use a
List<KeyValuePair<string, int>> MyList = new List<KeyValuePair<string, int>>();
to iterate through a 2D array of two different types as a List supports iteration. But then again, you cannot obtain the age of Angelina by MyList["Angelina"].Value but you would have to use MyList[0].Value.
But you could use a datatable as well. But it requires somewhat more work to initialize the table with its columns.
If you want to lookup/set a boolean by control name, you could use a Dictionary<string, bool>.
Use Dictionary<string,bool>.
If, for some reason, you really need an array, try object[,] and cast its values to the types you want.
Another way of doing it is to create an array of type object, and then add this to an arraylist.
Here is some sample code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
namespace Collections
{
class Program
{
static void Main(string[] args)
{
ArrayList ar = new ArrayList();
object[] o = new object[3];
// Add 10 items to arraylist
for (int i = 0; i < 10; i++)
{
// Create some sample data to add to array of objects of different types.
Random r = new Random();
o[0] = r.Next(1, 100);
o[1] = "a" + r.Next(1,100).ToString();
o[2] = r.Next(1,100);
ar.Add(o);
}
}
}
}
"A multi-dimensional array is an array:
all elementsin all dimensions have the same type"
Actually you can do it with a List. I suggest you take a look at Tuples.
How to easily initialize a list of Tuples?
You can use a list of type object too if you want
Like so :
List<List<object>> Dates = new List<List<object>>() { };
Dates.Add(new List<object>() { 0 ,"January 1st" });

Initialization of Array in C# [duplicate]

This question already has answers here:
What is the default value of a member in an array?
(4 answers)
Closed 3 years ago.
I would like to ask some rather basic question (I presume) the answer to which seems to elude me. In the following code I am trying to load an array with a csv file (; separated) that contains two columns (string Name, int Score).
For simplicity I have commented out the loop I want to use to transfer this file onto an array and I am just loading the 2nd element. For some reason unless I use (scoreobj[1] = new HighScore();) I get a null reference.
Why do I need to do that? Haven't I already initialized the scoreobj[] object at the beginning?
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp1
{
public class HighScore
{
public string Name { get; set; }
public int Score { get; set; }
public static void LoadHighScores(string filename)
{
string[] scoredata = File.ReadAllLines("C:/Users/User/Desktop/Test.csv");
HighScore[] scoreobj = new HighScore[scoredata.Length];
scoreobj[1] = new HighScore();
scoreobj[1].Name = scoredata[1].Split(';')[0];
//for (int index = 0; index < scoredata.Length; index++)
//{
// scoreobj[index].Name = scoredata[index].Split(',')[0];
// scoreobj[index].Score = Convert.ToInt32(scoredata[index].Split(';')[1]);
//}
Console.WriteLine(scoreobj[1].Name);
}
}
}
Because just declaring an index of a specific size does not create any element of type HighScore,. Instead you just reserve some memory. In other words: just because you have a bag does not put any potatoes in it. You have to go to the market and put potatoes into your bag yourself.
You could even create an instance of a derived class and put it into the exact same array. How would the compiler in this case know which class you want to instantiate?
class Foo { ... }
class Bar { ... }
var array = new Foo[3]; // how would anyone know if you want three Foo-instances or 3 Bar-instances? or a mix?
The compiler can't know which type you want to instantiate and thus won't create those instances. So you have to create the instance yourself.
But even without a derived class, your constructor may have parameters, which compiler can't guess:
class HighScore
{
public HighScore(string name, int score) { ... }
}
var array = new HighScore[3]; // how to set the parameters for the instances???
That's why your object just contains no instances, but just the types default-value, which is null for reference-types.
HighScore[] scoreobj = new HighScore[scoredata.Length]; creates an array of the specified length (scoredata.Length), but containing no objects.
Yo need to assign an object at each index, which could be done as follows:
for (int i = 0; i < scoredata.Length; i++)
{
scoreobj[i] = new HighScore();
scoreobj[i].Name = scoredata[i].Split(';')[0];
}

Cannot convert void to list [duplicate]

This question already has answers here:
c# sort a list by a column alphabetically
(2 answers)
Closed 6 years ago.
I am trying to write my first c# program and I can't keep getting the error below. Can someone explain why I am getting this error? Everything has a type when it is declared, where is the void coming from? I am writing the code on https://repl.it/languages/csharp if it is important.
using System;
using System.Linq;
using System.Collections.Generic;
class MainClass {
public static void Main (string[] args) {
List<string> mylist = new List<string>() { "2","1","2","3","3","4" };
mylist=mylist.Sort();
foreach(var item in mylist)
{
Console.Write(item.ToString());
}
}
}
Error:
Cannot implicitly convert type `void' to `System.Collections.Generic.List<string>'
List<T>.Sort returns void as it actually modifies the List it is called on (it doesn't return a new collection). Hence assigning the method's return value to a List is a compile error.
If you want a sort that does not modify the underlying collection, consider using OrderBy and ToList if you want to eager-enumerate the result.
mylist.Sort(); doesn't return List, it returns void, you shouldn't assign it to a list.
After calling Sort your entire list is already sotred.

Use LINQ to store in Hashtable [duplicate]

This question already has answers here:
Convert Linq Query Result to Dictionary
(4 answers)
Closed 8 years ago.
Is it possible to use LINQ to get data from DB and store it in Dictionary.
I can do LINQ and store it in a List<Class_B> and then iterate through the list and store it in Dictonary<Class_A,List<Class_B>>. But is it possible to directly store in the Dictionary?
System.Linq.Enumerable has a ToDictionary method.
Here's an example from dotnetperls.com:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Example integer array.
int[] values = new int[] { 1, 3, 5, 7 };
// First argument is the key, second the value.
Dictionary<int, bool> dictionary = values.ToDictionary(v => v, v => true);
// Display all keys and values.
foreach (KeyValuePair<int, bool> pair in dictionary)
{
Console.WriteLine(pair);
}
}
}

Defining two dimensional Dynamic Array with different types

I want to create two dimension array of different type like I can add to that array two values one of them is controlname and second is boolean value.
You can't do that. Instead, you should create a class that contains these two properties, then you can create an array of that type:
public class MyClass
{
public string ControlName {get;set;}
public bool MyBooleanValue {get;set;}
}
public MyClass[] myValues=new MyClass[numberOfItems];
Or, as Anders says, use a dictionary if one of the properties is meant to be used to perform lookups.
A dictionary will work for what you are trying to do then.
Dictionary<string, bool> controllerDictionary = new Dictionary<string, bool>();
To set a value
if (controllerDictionary.ContainsKey(controllerName))
controllerDictionary[controllerName] = newValue;
else
controllerDictionary.Add(controllerName, newValue);
To get a value
if (controllerDictionary.ContainsKey(controllerName))
return controllerDictionary[controllerName];
else
//return default or throw exception
You can't to that with an array.
Perhaps you should be using a Dictionary?
A generic dictionary of Dictionary<string,bool> appears to be the kind of thing that will work for your description.
It depends on how you want to use your array. Do you want to look up the value by a key, or by its index? Konamiman suggested a class. But a class with two types is nothing more than a Dictionary<type of key, type of value>.
You can use a dictionary if you want to obtain the value by a key.
Like so:
Dictionary<string, int> MyDict = new Dictionary<string, int>();
MyDict.Add("Brutus", 16);
MyDict.Add("Angelina", 22);
int AgeOfAngelina = MyDict["Angelina"];
Now the disadvantage of a dictionary is that, you can't iterate over it. The order is undetermined. You can not use MyDict[0].Value to obtain the age of Brutus (which is 16).
You could use a
List<KeyValuePair<string, int>> MyList = new List<KeyValuePair<string, int>>();
to iterate through a 2D array of two different types as a List supports iteration. But then again, you cannot obtain the age of Angelina by MyList["Angelina"].Value but you would have to use MyList[0].Value.
But you could use a datatable as well. But it requires somewhat more work to initialize the table with its columns.
If you want to lookup/set a boolean by control name, you could use a Dictionary<string, bool>.
Use Dictionary<string,bool>.
If, for some reason, you really need an array, try object[,] and cast its values to the types you want.
Another way of doing it is to create an array of type object, and then add this to an arraylist.
Here is some sample code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
namespace Collections
{
class Program
{
static void Main(string[] args)
{
ArrayList ar = new ArrayList();
object[] o = new object[3];
// Add 10 items to arraylist
for (int i = 0; i < 10; i++)
{
// Create some sample data to add to array of objects of different types.
Random r = new Random();
o[0] = r.Next(1, 100);
o[1] = "a" + r.Next(1,100).ToString();
o[2] = r.Next(1,100);
ar.Add(o);
}
}
}
}
"A multi-dimensional array is an array:
all elementsin all dimensions have the same type"
Actually you can do it with a List. I suggest you take a look at Tuples.
How to easily initialize a list of Tuples?
You can use a list of type object too if you want
Like so :
List<List<object>> Dates = new List<List<object>>() { };
Dates.Add(new List<object>() { 0 ,"January 1st" });

Categories