开发者

testing for one item in dictionary<k,v>

开发者 https://www.devze.com 2022-12-28 01:18 出处:网络
I\'m using VS 2005 fx2.0. If I know my Dictionary contains only 1 item how do I开发者_C百科 get to it?

I'm using VS 2005 fx2.0.

If I know my Dictionary contains only 1 item how do I开发者_C百科 get to it?

Thanks, rod


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


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; 


Graviton is correct but to be a bit safer (in the event that there is more than one item) you could do this:

yourDictionary.First();

And to be even safer you could do this (in the event that the dictionary was empty as well):

yourDictionary.FirstOrDefault();


Just iterate over all elements of Dictionary (in this case only one)

foreach (KeyValuePair<v, k> keyValue in dictionary)
            {

            }


dictionary.SingleOrDefault();
0

精彩评论

暂无评论...
验证码 换一张
取 消