我有(或想要)这样的代码:
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>'
}
Run Code Online (Sandbox Code Playgroud)
我也试过像这样改变违规行:
if ( entry != default(KeyValuePair<string,int>) )
Run Code Online (Sandbox Code Playgroud)
但是这也会产生编译错误:
Operator '!=' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair<string,int>' and 'System.Collections.Generic.KeyValuePair<string,int>'
Run Code Online (Sandbox Code Playgroud)
什么给这里?
Jon*_*eet 47
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;
}
}
Run Code Online (Sandbox Code Playgroud)
或者,项目为可空类型:
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>
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*Jon 39
这样做:
if ( entry.Key != null )
Run Code Online (Sandbox Code Playgroud)
问题是,该FirstOrDefault方法返回一个KeyValuePair<string, int>这是一个值类型,因此它不能永远null.您必须确定这个值是通过检查,如果其至少一个已发现Key,Value性能都有它的默认值.Key是类型的string,所以null考虑到字典不能有一个带null键的项目,检查是否有意义.
您可以使用的其他方法:
var entry = dict.Where(e => e.Value == 1)
.Select(p => (int?)p.Value)
.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
这会将结果投影到一个可以为空的int集合中,如果它是空的(没有结果),则会得到一个null - 你无法将其误int认为是成功的搜索会产生的.
小智 6
无论Key和Value的类型如何,您都可以这样做:
static void Main(string[] args)
{
var dict = new Dictionary<int, string>
{
{3, "ABC"},
{7, "HHDHHGKD"}
};
bool found = false;
var entry = dict.FirstOrDefault(d => d.Key == 3 && (found=true));
if (found)
{
Console.WriteLine("found: " + entry.Value);
}
else
{
Console.WriteLine("not found");
}
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我认为最清晰的代码是这样的:
if (dict.ContainsValue(value))
string key = dict.First(item => item.Value == value).Key;
else
// do somehing else
Run Code Online (Sandbox Code Playgroud)
虽然从速度的角度来看它并不好,但没有更好的解决方案。这意味着将使用慢速搜索第二次搜索字典。应该通过提供一个方法“bool TryGetKey(value)”来改进 Dictionary 类。这看起来有点奇怪——因为人们认为字典被用于另一个方向——但有时向后翻译是不可避免的。