Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing for one item in dictionary<k,v>

I'm using VS 2005 fx2.0.

If I know my Dictionary contains only 1 item how do I get to it?

Thanks, rod

like image 658
Rod Avatar asked Dec 05 '22 02:12

Rod


2 Answers

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

Or make a method that do that, like:

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

like image 168
digEmAll Avatar answered Dec 17 '22 19:12

digEmAll


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

var item = Dictionary<k,v>.Single();
var key = item.Key;
var value =item.Value; 
like image 31
Graviton Avatar answered Dec 17 '22 19:12

Graviton