我有(或想要)这样的代码:
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 …Run Code Online (Sandbox Code Playgroud) 我有一个代码:
var status = ...
var StatusMapping = new Dictionary<AnotherStatus, IList<Status>>
{
{
AnotherStatus,
new List<Status>
{
Status1,
Status2
}
}
}
foreach (var keyValuePair in StatusMapping)
{
if (keyValuePair.Value.Contains(status))
{
return keyValuePair.Key;
}
}
throw Exception();
Run Code Online (Sandbox Code Playgroud)
我是C#的新手,从Java切换到了C#。在Java中,可以很容易地做到这一点:
return StatusMapping
.entrySet()
.stream()
.filter(e -> e.getValue().contains(status))
.map(Map.Entry::getKey)
.findFirst()
.orElseThrow(() -> new Exception());
Run Code Online (Sandbox Code Playgroud)
有没有办法用LINQ做到这一点?