Check if KeyValuePair exists with LINQ's FirstOrDefault

本文讨论了如何使用 LINQ 方法检查 Dictionary 对象中是否存在特定值,包括如何验证返回的键值对是否有效,以及替代方法如使用 ContainsValue 和 Any 方法进行值搜索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值