Dictionary.FirstOrDefault()如何确定的结果,发现发现、结果、Dictionary、FirstOrDefault

2023-09-04 07:12:58 作者:你是我的故事

我有(或希望有)一些code是这样的:

I have (or wanted to have) some code like this:

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>'
}

我也试图改变问题的行是这样的:

I also tried changing the offending line like this:

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

但是,这也给了编译错误:

But that also gives a compile error:

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

是什么让这里?

What gives here?

推荐答案

乔恩的答案将与词典&LT;字符串,INT&GT; ,因为不能有一个空在字典中的键值。它不会与词典&LT工作;整型​​,字符串&GT; ,但是,因为这不的再present 的空键值。 ..失败的模式最终会为0的关键。

Jon's answer will work with Dictionary<string, int>, as that can't have a null key value in the dictionary. It wouldn't work with Dictionary<int, string>, however, as that doesn't represent a null key value... the "failure" mode would end up with a key of 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;
    }
}

Alternativel,项目可空类型:

Alternativel, project to a nullable type:

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>
}