Check if KeyValuePair exists with LINQ's FirstOrDefault
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.
最新文章
- C#中如何创建PDF网格并插入图片
- iOS模态弹出半透明视图控制器
- AVL-tree
- js数字、字符串、数组之间的转化
- Oracle警告、跟踪文件(10046、死锁等跟踪)
- Delphi关于记录文件的操作
- superobject中 JavaToDelphiDateTime的使用
- Jquery 中toggle的用法举例
- Android tabhost下的activity怎样获取传来的值
- Java单实例的最佳写法
- Opencv学习笔记(六)SURF学习笔记
- XStream的使用方法、简单使用方法、xml的解析方法
- 多个项目MyEclipse中启动出现OutOfMemoryError: PermGen space如何解决
- Linux(CentOS) 查看当前占用CPU或内存最多的K个进程
- archlinux下安装acroread打开pdf
- JavaScript循环语句-6---for语句,while语句的应用逻辑
- 关于dict的formkeys方法注意
- HDU 1084:What Is Your Grade?
- Unix环境高级编程(六)进程控制
- 【转】Unity Scene场景自定义坐标轴