c# - 如何使用 LINQ 在字典中查找元素

标签 c# linq

我有一个代码:

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(); 

我刚接触 C#,是从 Java 转过来的。在 Java 中,它很容易像这样完成:

return StatusMapping
    .entrySet()
    .stream()
    .filter(e -> e.getValue().contains(status))
    .map(Map.Entry::getKey)
    .findFirst()
    .orElseThrow(() -> new Exception());

有没有办法用 LINQ 做到这一点?

最佳答案

首先,如果您经常这样做,您可能需要考虑另一种数据结构。字典并不是真正用于频繁“基于值的某些方面的查找”。

哦,在 C# 中更简单 :)

var key = StatusMapping.First(x => x.Value.Contains(status)).Key;

First()如果没有任何匹配项,将抛出异常。

如果你想以默认值结束,你可以使用:

var key = StatusMapping.FirstOrDefault(x => x.Value.Contains(status)).Key;

这将导致 keyAnotherStatus 的默认值(或任何键类型)。

请注意,这只能完全像这样工作,因为 KeyValuePair<,>是值类型,所以默认值是非空的,带有默认键。如果您有一系列 reference 类型,您将需要如下内容:

var property = sequence.FirstOrDefault(whatever)?.Property;

... 其中 ?.是空条件运算符。

关于c# - 如何使用 LINQ 在字典中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55420571/

相关文章:

c# - MVVM命令错误

C# 无法创建实例,因为 Type.ContainsGenericParameters 为真

c# - 如何正确加载程序集

c# - 输出所有命令行参数

c# - 使用 Linq 关联防止空异常

c# - 如何使用 LINQ 避免冗余列表

c# - 在 3D 中排序点

c# - 如何在 LINQ 中询问 "Is there exactly one element satisfying condition"?

c# - 将多个 ORDER BY 子句添加到 NHibernate 查询会引发异常

c# - 如何根据DataType组合 "collectionResult"