mbadawi23
mbadawi23

Reputation: 1071

Linq: Select KeyValuePair from dictionary where value is a list of objects

I have a field that looks like:

public Dictionary<ClassA, List<ClassB>> MyDict;

Assume that:

public class ClassA 
{
    public string Name;
    public int Id;
 }

public class ClassB 
{
    public string Tag;
    public string Text;
 }

I'm trying to define a query that is of IEnumerable<KeyValuePair<ClassA,IEnumerable<ClassB>> type where I define a condition on the value of ClassB.Tag. I tried things like:

IEnumerable<KeyValuePair<ClassA,IEnumerable<ClassB>> q =
    MyDict.Where(pair => pair.Value.Any(b => b.Tag == "a tag"));

But obviously the above is not what I need because it returns the whole List<ClassB> if any item matches that condition, while what I want is to return an IEnumrable or a List of items that match the condition.

Upvotes: 1

Views: 5416

Answers (1)

Travis J
Travis J

Reputation: 82267

dotNetFiddle demo

You need to construct the IEnumerable from a call to ToDictionary, where you use a projection to only take the matching BClass from the list and only take the result from that set where values in the BClass list were actually matched.

IEnumerable<KeyValuePair<ClassA,List<ClassB>>> q = MyDict.ToDictionary(
    k => k.Key, 
    k => k.Value.Where(b => b.Tag == "10").ToList()
).Where(kv => kv.Value.Any());

Upvotes: 3

Related Questions