首页 > 解决方案 > c#:带有多个条件的字典的Linq

问题描述

所以我有List而且Dictionary<string, object> 我想用 2 个列名的条件解析 1 个项目:

如果我搜索列名为“Id”的 1 个项目,我会这样做:

var collection ....

var result = collection.OfType<Dictionary<string, object>>()
    .SelectMany(d => d.Where(x => x.Key == "id"))
    .Where(x => x.Value?.ToString() == "1234")
    .ToList();

在这里,我正在搜索列名的项目Id,它的值是1234,这工作正常。

现在我想添加一些条件:

我想搜索具有列名Id和值1234以及列名的项目,"Class"并且我想获取"Class"列名值。

有什么建议么 ?

标签: c#linqdictionary

解决方案


从根本上说,您SelectMany正在展平所有字典中的所有条目。这意味着当您获得键/值对时,您不知道哪对来自哪个字典。在您描述的情况下,您不想这样做。您想要筛选特定项目,然后选择每个项目的一个方面。

您可以只使用下面的代码。我假设那collection是 type List<Dictionary<string, object>>,所以你现在不需要你的OfType电话。

var result = collection
    // Filter to items with the correct ID.
    .Where(d => d.TryGetValue("Id", out var id) && id?.ToString() == "1234")
    // Filter to items containing a "Class" entry
    .Where(d => d.ContainsKey("Class"))
    // Select the class
    .Select(d => d["Class"])
    .ToList();

推荐阅读