Mike
Mike

Reputation: 3284

Grouping Query Linq

I have a 3 classes:

Class 1:
public IEnumerable<double> Values;
public Class2 class2Instance;

Class2:
public string Name;
public Class3 class3Instance;

Class3:
public long Id;
public string Name;

Now I have got a huge collection of Class1, something like an IEnumerable<Class1>, and I have the Class3 Id. How can I use an efficient LINQ query to get all Class1 instances which are relevant to Class2 which matches with Class1 ID?

Upvotes: 1

Views: 68

Answers (2)

Aducci
Aducci

Reputation: 26644

var query = from x in class1Enumerable
            where x.class2Instance != null
            where x.class2Instance.class3Instance != null
            where x.class2Instance.class3Instance.id == yourId
            select x;

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500525

Well if you've only got a sequence of them, you've got to go through all of them:

var matches = collection.Where(x => x.class2Instance.class3Instance.Id == id);

If you need to do this regularly, you may want to build a Dictionary<long, Class1> instead.

(I'm assuming that neither class2Instance nor class3Instance can be null. If they can, you'll need to use code like Aducci's.)

Upvotes: 4

Related Questions