Testing for one element in the dictionary <k, v>

I am using VS 2005 fx2.0.

If I know that my dictionary contains only 1 element, how do I get to it?

Thanks, Core

+4
source share
5 answers

The only way (with framework 2.0) is to iterate over it with foreach.

Or create a method that does this, for example:

public static T GetFirstElementOrDefault<T>(IEnumerable<T> values) { T value = default(T); foreach(T val in values) { value = val; break; } return value; } 

It works with all IEnumerable and in your case T is KeyValuePair

+5
source

Make sure you have using System.Linq; . The command below will get a pair of dictionary key values

 var item = Dictionary<k,v>.Single(); var key = item.Key; var value =item.Value; 
+5
source

Graviton is correct, but to be a little safer (in case there are more than one element), you can do this:

 yourDictionary.First(); 

And to be more secure, you could do this (if the dictionary was also empty):

 yourDictionary.FirstOrDefault(); 
+5
source

Just iterate over all the elements of the dictionary (in this case, only one)

 foreach (KeyValuePair<v, k> keyValue in dictionary) { } 
+1
source
 dictionary.SingleOrDefault(); 
0
source

Source: https://habr.com/ru/post/1307460/


All Articles