Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

If i search for 1 item with column name "Id" i do it this way:

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.

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.

Any suggestions ?

like image 826
Erofh Tor Avatar asked Mar 04 '23 10:03

Erofh Tor


1 Answers

Fundamentally your SelectMany is flattening all the entries from all the dictionaries. 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.

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();
like image 148
Jon Skeet Avatar answered Mar 15 '23 16:03

Jon Skeet