I am new to the C#/.Net and have a problem with class Dictionary. I created a dictionary of groups and added an item (or more items, now it doesn't matter):
Dictionary<int, ListViewGroup> groups = new Dictionary<int, ListViewGroup>();
groups.Add(1, new ListViewGroup("Group1"));
I would like to find my group by its key. In documentation it says that there is an Item property which I can access directly or by indexer. However, when I try to access it directly:
ListViewGroup g = groups.Item(1);
my compiler says that there is no definition for property Item in Dictionary class. Can anyone explain this to me please? Thank you.
Access Dictionary Elements The Dictionary can be accessed using indexer. Specify a key to get the associated value. You can also use the ElementAt() method to get a KeyValuePair from the specified index.
Dictionary is a collection of keys and values in C#. Dictionary is included in the System. Collection. Generics namespace. To declare and initialize a Dictionary −
Item is an indexer, you can verify it by looking at definition:
public TValue this[TKey key] { get; set; }
Simply use indexer syntax to access elements by key:
ListViewGroup g = groups[1];
Console.WriteLine (g.Header); //prints Group1
Note: this will throw KeyNotFoundException
if no entry with such key would be present in groups
dictionary. For example groups[2]
will throw an exception in your case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With