I am confused as to how to use
Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
constructor of Dictionary Class in C#. A working example will be very helpful.
Thanks
Satish Chandra
With the constructor you mentioned you can pass an already existing Dictionary as parameter.
e.g.:
Dictionary<int,string> firstDictionary = new Dictionary<int, string> { { 0, "0" }, { 1, "hallo" } };
Dictionary<int,string> secondDictionary;
void InitSecondDict()
{
secondDictionary = new Dictionary<int,string>(firstDictionary);
}
What this constructor does is copying the elements from "firstDictionary" into the new Dictionary<int,string>-object "secondDictionary"
Dictionary<string, string> openWith = new Dictionary<string, string>();
More info and examples on Micrsoft docs
Related
I have to write a Dictionary which will be
Dictionary<int, Dictionary<string, string>> dictionary = new Dictionary<int, Dictionary<string, string>>() { };
so later i'll just check and get values like
if (dictionary[index].key* == value) { stuff; } //*or maybe it's [index][key], that's not the matter
I just don't know and understand how to write the various elements inside the dictionary (i already searched here and online), the proper syntax, anything i try gets an error. Hope you can help, thank you in advance!
The name index isn't really appropriate, because dictionaries don't use indices they use keys.
However, to add a new sub-dictionary:
dictionary[i] = new Dictionary<string, string>();
To add / replace a value in an existing sub-dictionary:
dictionary[i][key] = value;
If you want to safely insert a new value when a sub-dictionary may or may not have been created, you could create an extension method:
public static void Insert(this Dictionary<int, Dictionary<string, string>> dict, int i, string key, string value)
{
if (!dict.ContainsKey(i)) dict[i] = new Dictionary<string, string>();
dict[i][key] = value;
}
Then use like this:
dictionary.Insert(1, "SomeKey", "SomeValue");
Just note that this will overwrite keys in the sub-dictionary if the same key is inserted more than once.
To insert into this object:
Dictionary<int, Dictionary<string, string>> dictionary = new Dictionary<int, Dictionary<string, string>>() { };
You'll need to do multiple inserts. So something like:
//create the first level and instanciate a new dictionary object
dictionary.Add(1234, new Dictionary<string, string>());
//insert into the dictionary created above
dictionary[1234].Add("test", "test");
dictionary[1234] here returns a Dictionary<string, string> where 1234 is the key added in dictionary.Add(1234, new Dictionary<string, string>());
How about using collection initialisers? This is great if you have constant values that you want the dictionary to contain:
var dictionary = new Dictionary<int, Dictionary<string, string>>() {
[111] = new Dictionary<string, string> {
["nested key1"] = "value 1",
["nested key2"] = "value 2",
["nested key3"] = "value 3",
["nested key4"] = "value 4",
},
[222] = new Dictionary<string, string> {
["nested key5"] = "value 5",
["nested key6"] = "value 6",
["nested key7"] = "value 7",
["nested key8"] = "value 8",
},
};
dictionary has type Dictionary<int, Dictionary<string, string>>, so var b = dictionary[3] has type Dictionary<string, string>, and to get an entry of b use syntax b["Hello"] to get a string.
If you want to write them in one clause, use (dictionary[3])["Hello"]. Since operator[] is left-associative, (dictionary[3])["Hello"] can be written as dictionary[3]["Hello"].
I am confused I am trying to manually add entries to a Dictionary but its throwing an error at the first comma. Any help is appreciated thank you.
private Dictionary<string, Dictionary<string, string>> packData =
new Dictionary<string, Dictionary<string, string>>()
{
{
"Test", //issue here
{
"Test" , "Test"
}
};
};
You'll want to be explicit about the inner dictionary:
new Dictionary<string, Dictionary<string, string>>()
{
{
"Test",
new Dictionary<string, string>
{
"Test" , "Test"
}
};
};
The rule to follow here is "imagine if the thing in the braces was replaced with a call to Add". In your original code, we would have lowered this to:
temp = new Dictionary<string, Dictionary<string, string>>();
temp.Add("Test", { "Test", "Test" });
Which is not legal code. But
temp = new Dictionary<string, Dictionary<string, string>>();
temp.Add("Test", new Dictionary<string, string>(){ "Test", "Test" });
is legal, and in turn corresponds to
temp = new Dictionary<string, Dictionary<string, string>>();
temp2 = new Dictionary<string, string>();
temp2.Add("Test", "Test");
temp.Add("Test", temp2);
I often find when I'm confused that it helps to "lower" the code into its more basic form to understand what's going on.
There are some situations in which the compiler is smarter about understanding the intended meaning of nested braces like in your original code, but unfortunately this is not one of them. See the specification for more details about what is and is not supported; you'll want to search for "object initializers" and "collection initializers".
Apologies in advance; I am on day 3 of trying to learn C#.
I am instructed to build a hashset of dictionaries; no problem. I see that that has been built. I now need to iterate over the hashset and copy the entries to a new list if the dictionary's key != a particular string. Could someone kindly explain the proper syntax for achieving this seemingly simple task?
var goodSongs = new List<Dictionary<string,string>>();
var allSongs = new HashSet<Dictionary<string, string>>();
Dictionary<string, string> meatloaf = new Dictionary<string, string>();
meatloaf.Add("Meatloaf", "Paradise By The Dashboard Light");
Dictionary<string, string> aerosmith = new Dictionary<string,string>();
aerosmith.Add("Aerosmith", "Cryin'");
Dictionary<string, string> nickelback = new Dictionary<string, string>();
nickelback.Add("Nickelback", "Rockstar");
allSongs.Add(nickelback);
allSongs.Add(aerosmith);
allSongs.Add(meatloaf);
//foreach loop to iterate dictionaries goes here
Goal - To get unstuck, hope to learn C#, and decide if I want to keep going down this rabbit hole. Thanks to all.
Here is an example of how to iterate through the hashset and then the dictionary:
var all = new HashSet<Dictionary<string, string>>();
Dictionary<string, string> newDict = new Dictionary<string, string>();
newDict.Add("M", "T");
all.Add(newDict);
foreach(Dictionary<string,string> dict in all)
{
foreach(KeyValuePair<string,string> pair in dict)
{
string key = pair.Key;
string value = pair.Value;
}
}
I am using a Xamarin.Forms Picker and it's being populated by a List<KeyValuePair<string, string>>. The issue is that it isn't displaying the way I would like.
XAML:
<Picker x:Name="VersionPicker" ItemsSource="{Binding}"/>
C#:
Dictionary<string, string> VersionDictionary = new Dictionary<string, string>()
{
{ "asv1901", "American Standard Version" },
{ "bbe", "Bible In Basic English" },
};
List<KeyValuePair<string, string>> VersionList = VersionDictionary.ToList();
VersionPicker.BindingContext = VersionList;
What it produces is like this...
[asv1901, American Standard Version]
I would like Picker to have something along these lines...
American Standard Version (asv1901)
Is there a way to do this? XAML or C# would be fine (since it's purely a visual change, I was thinking XAML or a converter might make the most sense).
A shout-out to jdweng (since he/she just did a comment and not an answer)...
Dictionary<string, string> VersionDictionary = new Dictionary<string, string>()
{
{ "asv1901", "American Standard Version" },
{ "bbe", "Bible In Basic English" },
};
// take the dictionary<string, string>, turn it into an ienumerable<keyvaluepair<string, string>>, use linq to output the contents, format a new string based on those contents, turn it into list<string>
// "Bible In Basic English (bbe)"
var VersionList = VersionDictionary.AsEnumerable().Select(x => string.Format("{0} ({1})", x.Value, x.Key)).ToList();
VersionPicker.BindingContext = VersionList;
To get that choice back to the appropriate format...
private void VersionPicker_SelectedIndexChanged(object sender, EventArgs e)
{
var selecteditem = VersionPicker.SelectedItem.ToString();
// single quotes make it type Char while double quotes make it type String
Char delimiter = '(';
// create an array from the string separated by the delimiter
String[] selecteditemparts = selecteditem.Split(delimiter);
// take off the end space
var selecteditemvalue = selecteditemparts[0].Substring(0, (selecteditemparts[0].Length - 1));
// take off the end )
var selecteditemkey = selecteditemparts[1].Substring(0, (selecteditemparts[1].Length - 1));
}
As a secondary option (and the one I ended up using)...
Dictionary<string, string> VersionDictionary = new Dictionary<string, string>()
{
{ "asv1901", "American Standard Version" },
{ "bbe", "Bible In Basic English" },
};
var VersionList = new List<string>();
// keyvaluepair is a single instance and dictionary is a collection of keyvaluepairs
foreach (KeyValuePair<string, string> version in VersionDictionary)
{
var key = version.Key.ToUpper();
var value = version.Value;
// "Bible In Basic English (BBE)"
VersionList.Add(string.Format("{0} ({1})", value, key));
}
It just makes more sense to my rather novice coding brain. I'm sure jdweng's linq example is much more concise.
I've 4 Dictionaries like,
Dictionary<string, string> home = new Dictionary<string, string>();
Dictionary<string, string> home1 = new Dictionary<string, string>();
Dictionary<string, string> away1 = new Dictionary<string, string>();
Dictionary<string, string> away2= new Dictionary<string, string>();
now I want to perform Assert for each of them on their Keys and values. How should i do that ?
i was thinking to adding them as below,
var dic = new[] { home , home1 , away1 , away2};
and then use Switch but it seems difficult as switch can't be used on array. So how should i approach this one ?
Why don't you create a function for asserting a dictionary, then loop over the array and call it, something like this:
foreach (var element in dic)
{
AssertOnDictioanry(element);
}
Hope this was useful.