I'm trying to initialize a dictionary with string elements as keys and int[] elements as values, as follows:
System.Collections.Generic.Dictionary<string,int[]> myDictionary;
myDictionary = new Dictionary<string,int[]>{{"length",{1,1}},{"width",{1,1}}};
But the debugger keeps saying: "Unexpected symbol '{'".
Could you tell me what's wrong with the above code?
Thank you!
I am not sure for c# but the following works in Java for example:
instead of
{1,1}
try
new int[]{1,1}
or
new[]{1,1}
Below are two examples that work. The second example only works inside a method. The first example will work inside a method or outside a method in a class.
The initial code was missing the () for the new Dictionary() statement which is probably what gave the "{" unexepcted symbol error. The "new Int[]" is also required
class SomeClass
{
Dictionary<string, int[]> myDictionary = new Dictionary<string, int[]>()
{
{"length", new int[] {1,1} },
{"width", new int[] {1,1} },
};
public void SomeMethod()
{
Dictionary<string, int[]> myDictionary2;
myDictionary2 = new Dictionary<string, int[]>()
{
{"length", new int[] {1,1} },
{"width", new int[] {1,1} },
};
}
}
System.Collections.Generic.Dictionary<string,int[]> myDictionary;
myDictionary = new Dictionary<string, int[]> { { "length", new int[] { 1, 1 } }, { "width", new int[] { 1, 1 } } };
You will need to specify that it's an array that you are inserting in to your Dictionary:
System.Collections.Generic.Dictionary<string, int[]> myDictionary;
myDictionary = new Dictionary<string, int[]> {{"length", new int[]{1,2}},{ "width",new int[]{3,4}}};
In addition to all good answers you can also try this.
Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();
If possible prefer List<> over arrays as resizing is difficult in Arrays. You can not delete an element from an array. But an element can be deleted from List.
Related
I am currently programming using Unity and C#, and I have trouble linking a string value to a function using a dictionary.
I think of a code looking like this :
private string name;
void function1()
{
// code
}
private Dictionary<string, ?function?> nameToFunction = new Dictionary<string, ?function?>();
// The part between interrogation marks being unknown to me
// Trying to call the function with the name
nameToFunction[name]
I am sorry if my question isn't relative, or if there are simpler solutions I haven't thought of, but I am starting to learn programming.
Thanks for your answers !
Here are some examples:
private Dictionary<string, Action> actionDict = new Dictionary<string, Action>();
private Dictionary<string, Action<int>> actionParamDict = new Dictionary<string, Action<int>>();
private Dictionary<string, Func<int>> funcDict = new Dictionary<string, Func<int>>();
private Dictionary<string, Func<int, string>> funcParamDict = new Dictionary<string, Func<int, string>>();
You use Action e.g. Action<input type1, input type 2> if not returning a value, and Func<input type1, input type2, output type> to return a value. Both are defined with multiple numbers of inputs. So you could do Func<int,int,int,bool> for example, and Action<int,int,bool,string,string>
Here's a few examples:
var dict = new Dictionary<string, Action>();
dict.Add("Hello", () => Console.WriteLine("Hello"));
dict.Add("Goodbye", () => Console.WriteLine("Goodbye"));
dict["Hello"]();
dict["Goodbye"]();
var dict2 = new Dictionary<string, Action<string>>();
dict2.Add("HelloName", (name) => Console.WriteLine($"Hello {name}"));
dict2["HelloName"]("Fred");
var dict3 = new Dictionary<string, Func<int, int, int>>();
dict3.Add("ADD", (n1, n2) => n1 + n2);
dict3.Add("SUBTRACT", (n1, n2) => n1 - n2);
Console.WriteLine($"{dict3["ADD"](5, 10)}");
Console.WriteLine($"{dict3["SUBTRACT"](10, 5)}");
//create dict with var objects s0, s1, s2 dynamically
Dictionary<String, Object> dictionary = new Dictionary<String, Object>();
for(int i=0; i<sWPaths.Length-1; i++) {
string name = String.Format("s{0}", i);
dictionary[name] = i.ToString();
}
foreach (string p in found){
//change to your desired variable using string.format method
if(dictionary.Contains[p]) {
dictionary[p] = found.ToString();
}
}
I need save some values in array by key, for example:
var arr = ['N' => 1, 'M' => 2, 'P' => 3];
What data type I need use in C# for this?
I tried ArrayList class, but it does a simple array.
You want to use a Dictionary.
Complete example:
using System.Collections.Generic;
class Program
{
static void Main()
{
var arr = new Dictionary<char, int> {
{'N', 1},
{'M', 2},
{'P', 3},
};
foreach (var pair in arr) {
System.Console.WriteLine(pair.Key + ": " + pair.Value);
}
}
}
An IDictionary<string, int> should do the trick. Something like:
var arr = new Dictionary<string, int>
{
{ "N", 1 },
{ "M", 2 },
{ "P", 3 }
};
(Or even an IDictionary<char, int> if those values should be char instead of string.)
What you want to use is a System.Collections.Generic.Dictionary<char, int> or Dictionary<string, int> or you can also use an enum such as:
public enum EnumName
{
N,
M,
P
}
Try using Dictionary<string, int>, or Dictionary` if you wish to reference multiple types of values.
Have you tried a Hashtable, it would allow the key value pairs
Hello I'm trying to add values to this complex object. I'm trying to turn this object into JSON using JSON.Net.
Dictionary<string, List<Dictionary<string, int>>> MyList
= new Dictionary<string, List<Dictionary<string, int>>>();
The end result should look something like this: {
"Documents": [
{
"Title": ,
"DatePublished": ,
"DocumentURL": ,
"ThumbnailURL": ,
"Abstract": ,
"Sector": "",
"Country": [
""
],
"Document Type": ""
}
I have tried this but didn't work:
MyList["Dictionary"][0].Add("test", 4);
If you have a Dictionary<string, int> dictA you can add items to this via
Dictionary<string, int> dictA = new Dictionary<string, int>();
dictA.Add("SomeString", 99);
Then to add this dictionary to your List<Dictionary<string, int>> use the following
List<Dictionary<string, int>> dictList = new List<Dictionary<string, int>>();
dictList.Add(dictA);
Now you can add this to your Dictionary<string, List<Dictionary<string, int>>> myList object via
Dictionary<string, List<Dictionary<string, int>>> myList =
new Dictionary<string, List<Dictionary<string, int>>>();
myList.Add("SomeString", dictList);
I hope this helps.
For what it's worth, here's a sample loop which shows how to use Dictionary.Add and the Collection Initalizer:
Dictionary<string, List<Dictionary<string, int>>> MyList =
new Dictionary<string, List<Dictionary<string, int>>>();
foreach (int i in Enumerable.Range(1, 100))
{
var list = new List<Dictionary<string, int>>();
foreach (int ii in Enumerable.Range(1, 100))
list.Add(new Dictionary<string, int>() { { "Item " + ii, ii } });
MyList.Add("Item " + i, list);
}
MyList.Add("key1", new List<Dictionary<string, int>());
MyList["key1"].Add(new Dictionary<String, int>());
etc.
Will need more detail from you to give much more than that I'm afraid.
Even though it looks complex, it really is quite simple:
Your dictionary takes keys of string, and values of List<Dictionary<string, int>>. So to add a value, that value should always be of type List<Dictionary<string, int>>.
I have a dictionary with a string as key and a List as value.
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
So for each key there are several string values associated with the key.
The Problem is that the list values conytains some whitespace that I need to get rid of and what I do is passing the values of each list value to a different list using the trim() method and then after the loop assign it back to the original list.
List<string> lstNoWhite = new List<string>();
foreach (var kvp in dict)
{
for(int i = 0; i < kvp.Value.Count; i++)
{
lstNoWhite.Add(kvp.Value[i].Trim());
}
kvp.Value = lstNoWhite;
}
I do however get the error...along the lines of that the list cannot be assigned to as it is read only.
Which is a better way of getting rid of the whitespace?
Try this code:
// source dictionary
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
// target dictionary
Dictionary<string, List<string>> target = new Dictionary<string, List<string>>();
// using LINQ extension methods
dict.ToList().ForEach(i =>
{
List<string> temp = i.Value.Select(x => x.Trim()).ToList();
target.Add(i.Key, temp);
});
You can slightly modify your code to get rid of intermediate list:
foreach (var kvp in dict)
{
for(int i = 0; i < kvp.Value.Count; i++)
{
kvp.Value[i] = kvp.Value[i].Trim();
}
}
This will trim all whitespace in all strings from lists
You can also do this:
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
// var --> Dictionary<string, List<string>>
var trimmedDict = dict.ToDictionary(
keyValue => keyValue.Key, // The key
keyValue => keyValue.Value.Select(s => s.Trim()).ToList() // The value, trim all the strings in the value-list
);
I have a method which takes a Dictionary<int, int> as a parameter
public void CoolStuff(Dictionary<int, int> job)
I want to call that method with one dictionary entry, such as
int a = 5;
int b = 6;
var param = new Dictionary<int, int>();
param.Add(a, b);
CoolStuff(param);
How can I do it in one line?
This is it, if you do not need the a and b variables:
var param = new Dictionary<int, int> { { 5, 6 } };
or even
CoolStuff(new Dictionary<int, int> { { 5, 6 } });
Please, read How to: Initialize a Dictionary with a Collection Initializer (C# Programming Guide)
var param = new Dictionary<int, int>() { { 5, 6 } };