简体   繁体   English

c#:Linq with Dictionary with multiple conditions

[英]c#: Linq with Dictionary with multiple conditions

So i have List of Dictionary<string, object> And i want to parse 1 item with condition of 2 column names: 所以我有Dictionary<string, object> List Dictionary<string, object>我想要解析1项条件的2列名称:

If i search for 1 item with column name "Id" i do it this way: 如果我搜索列名为“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();

Here i am search for item with column name Id that its value is 1234 and this works fine. 在这里,我搜索列名为Id ,其值为1234 ,这很好。

Now i want to add some condition: 现在我想添加一些条件:

I want to search for an item with column name Id and value 1234 and column name "Class" and i want to get the "Class" column name value. 我想搜索列名为Id且值为1234且列名为"Class"并且我想获取"Class"列名称值。

Any suggestions ? 有什么建议 ?

Fundamentally your SelectMany is flattening all the entries from all the dictionaries. 从根本上说你SelectMany所有的字典压扁的所有条目。 That means by the time you get the key/value pairs, you don't know which pair came from which dictionary. 这意味着当你获得键/值对时,你不知道哪一对来自哪个字典。 You don't want to do this in the case you've described. 在您描述的情况下,您不希望这样做。 You want to filter to specific items, then select one aspect of each item. 您想要过滤到特定项目,然后选择每个项目的一个方面。

You could just use the code below. 你可以使用下面的代码。 I'm assuming that collection is of type List<Dictionary<string, object>> , so you don't need the OfType call you've got at the moment. 我假设该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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM