码迷,mamicode.com
首页 > 其他好文 > 详细

Check if KeyValuePair exists with LINQ's FirstOrDefault

时间:2015-11-27 19:57:10      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

http://stackoverflow.com/questions/793897/check-if-keyvaluepair-exists-with-linqs-firstordefault

问题:

I have a dictionary of type

Dictionary<Guid,int>

I want to return the first instance where a condition is met using

var available = m_AvailableDict.FirstOrDefault(p => p.Value == 0)

However, how do I check if I‘m actually getting back a KeyValuePair? I can‘t seem to use != or == to check against default(KeyValuePair) without a compiler error. There is a similar thread here that doesn‘t quite seem to have a solution. I‘m actually able to solve my particular problem by getting the key and checking the default of Guid, but I‘m curious if there‘s a good way of doing this with the keyvaluepair. Thanks

 

 

If you just care about existence, you could use ContainsValue(0) or Any(p => p.Value == 0)instead? Searching by value is unusual for a Dictionary<,>; if you were searching by key, you could use TryGetValue.

One other approach:

       var record = data.Where(p => p.Value == 1)
            .Select(p => new { Key = p.Key, Value = p.Value })
            .FirstOrDefault();

This returns a class - so will be null if not found.

Check if KeyValuePair exists with LINQ's FirstOrDefault

标签:

原文地址:http://www.cnblogs.com/chucklu/p/5001438.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!