gpt4 book ai didi

c# - Dictionary.FirstOrDefault() 如何确定是否找到结果

转载 作者:IT王子 更新时间:2023-10-29 03:53:09 26 4
gpt4 key购买 nike

我有(或想要)这样的代码:

IDictionary<string,int> dict = new Dictionary<string,int>();
// ... Add some stuff to the dictionary.

// Try to find an entry by value (if multiple, don't care which one).
var entry = dict.FirstOrDefault(e => e.Value == 1);
if ( entry != null ) {
// ^^^ above gives a compile error:
// Operator '!=' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair<string,int>' and '<null>'
}

我也试过像这样更改违规行:

if ( entry != default(KeyValuePair<string,int>) ) 

但这也给出了一个编译错误:

Operator '!=' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair<string,int>' and 'System.Collections.Generic.KeyValuePair<string,int>'

这里有什么?

最佳答案

Jon 的回答适用于 Dictionary<string, int> ,因为它在字典中不能有空键值。它不适用于 Dictionary<int, string> ,但是,因为它不代表空键值...“失败”模式将以键 0 结束。

两种选择:

写一个TryFirstOrDefault方法,像这样:

public static bool TryFirstOrDefault<T>(this IEnumerable<T> source, out T value)
{
value = default(T);
using (var iterator = source.GetEnumerator())
{
if (iterator.MoveNext())
{
value = iterator.Current;
return true;
}
return false;
}
}

或者,转换到可空类型:

var entry = dict.Where(e => e.Value == 1)
.Select(e => (KeyValuePair<string,int>?) e)
.FirstOrDefault();

if (entry != null)
{
// Use entry.Value, which is the KeyValuePair<string,int>
}

关于c# - Dictionary.FirstOrDefault() 如何确定是否找到结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5424968/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com