Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Dictionary<TKey, TValue>.Item Property in C#

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.

like image 246
Wolf Avatar asked Jun 04 '13 12:06

Wolf


People also ask

How to access Dictionary items in C#?

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.

What is Dictionary object in C#?

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 −


1 Answers

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.

like image 71
Ilya Ivanov Avatar answered Oct 01 '22 00:10

Ilya Ivanov