Robert Lancaster
Robert Lancaster

Reputation: 289

LINQ query for Dictionary items in C#

I have a Dictionary where on of the members of DetailedObject is a List. I am trying to write a query against the Dictionary to return all of the items where the DetailedObject has a specific value for one of the fields in it's SubStructure. For example:

public struct SubStructure
{
  public int Id;
  public string SubSpecificFile;
}

public class DetailedObject  
{
  public int Id;
  public List<SubStructure> subs = new List<SubStructure>();
}

public Dictionary<int, DetailedObject> dict = new Dictionary<string, DetailedObject>();

Each SubStructure can appear inside zero or more DetailedObject instances.

I would, for example, like to query "dict" for each DetailedObject whose "subs" collection contains a SubStructure item with the Id of 3.

Upvotes: 0

Views: 8221

Answers (2)

Bala R
Bala R

Reputation: 108957

var result = dict1.Where(kvp => kvp.Value.subs.Any(ss => ss.Id == 3));

Upvotes: 6

spender
spender

Reputation: 120450

dict.Values.Where(d => d.subs.Any(ss => ss.Id == 3))

Upvotes: 7

Related Questions