c#:Linq with Dictionary with multiple conditions

Ero*_*Tor 4 c# linq dictionary

所以,我必须ListDictionary<string, object> ,我想解析1项与第2列名的条件:

如果我搜索列名为"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();
Run Code Online (Sandbox Code Playgroud)

在这里,我搜索具有Id其值的列名称的项目,1234这可以正常工作.

现在我想添加一些条件:

我想搜索具有列名Id,值1234和列名的项目"Class",我想获取"Class"列名值.

有什么建议 ?

Jon*_*eet 7

从根本上说您SelectMany是从压扁的所有条目所有的字典.这意味着当你获得键/值对时,你不知道哪一对来自哪个字典.在您描述的情况下,您不希望这样做.您想要过滤到特定项目,然后选择每个项目的一个方面.

你可以使用下面的代码.我假设它collection是类型的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();
Run Code Online (Sandbox Code Playgroud)