本文介绍了检查是否KeyValuePair与LINQ的FirstOrDefault存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类型的字典

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)

不过,我如何检查,如果我真的开始回KeyValuePair?我似乎无法使用!=或==对证默认(KeyValuePair)没有编译器错误。这里有一个类似的线程那不相当似乎有一个解决方案。我其实能够通过获取关键和检查的Guid的默认解决我特别的问题,但我很好奇,如果有与keyvaluepair这样做的一个很好的方式。谢谢

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

推荐答案

如果你只关心是否存在,你可以使用中的containsValue(0)任何(p => p.Value == 0)呢?通过的搜索值的是不寻常的词典<,> ;如果你被重点搜索,你可以使用 TryGetValue

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.

另外一个方法:

       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.

这篇关于检查是否KeyValuePair与LINQ的FirstOrDefault存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-15 08:16