相关疑难解决方法(0)

Dictionary.FirstOrDefault()如何确定是否找到了结果

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

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)

.net c# linq

48
推荐指数
4
解决办法
4万
查看次数

如何使用LINQ在Dictionary中查找元素

我有一个代码:

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做到这一点?

c# linq

2
推荐指数
1
解决办法
129
查看次数

标签 统计

c# ×2

linq ×2

.net ×1