SharpAffair
SharpAffair

Reputation: 5478

Linq - find element in nested collections

I have a generic list - SupportedTypeGroups.

Each SupportedTypeGroup has SupportedTypes property (generic list of SupportedType).

How to construct a Linq query to locate SupportedType with required name?

Upvotes: 7

Views: 5705

Answers (3)

Magnus
Magnus

Reputation: 46929

SupportedTypeGroups
  .SelectMany(s => s.SupportedTypes)
  .Where(s => s.name == "TheName");

Upvotes: 6

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

Assuming SupportedTypes is an IEnumerable<SupportedType>

from g in SupportedTypeGroups
where g.SupportedTypes.Where(t => t.Name == "magicName")
select g;

Assuming SupportedTypes is just a SupportedType property

from g in SupportedTypeGroups
where g.SupportedTypes.Name == "magicName"
select g;

Asasuming you just want the SupportedType

from tg in SupportedTypeGroups
from t in tg.SupportedTypes
where t.Name == "magicName"
select t;

Upvotes: 1

Snowbear
Snowbear

Reputation: 17274

var result = SupportedTypeGroups
             .SelectMany(g => g.SupportedTypes)
             .FirstOrDefault(t => t.Name == "TypeName");

Upvotes: 12

Related Questions