jdelator
jdelator

Reputation: 4251

Find parent based on children properties linq to sql

Lets say we have a sql relationship that can be modeled like this using C# classes

public class Parent 
{ 
  public int ID { get; set; } 
  public List<Child> Children { get; set; } 
} 

public class Child 
{ 
  public int ID { get; set; } 
  public Parent Parent { get; set; } 
  public int Number { get; set; } 
} 

I also know that the parent only has two children. I would I find all the parents where the children both satisfy a different criteria? Say One Child has a number = 0 and the other Child has a number = 1

Upvotes: 1

Views: 2730

Answers (3)

wcm
wcm

Reputation: 9281

Goin' out on a limb here...

(from p in context.Parents 
 where p.Children.Count == 2 
 where p.Children.Any(c => c.Number == 0) 
 select p).Where(p => p.Children.Any(c => c.Number == 1));

Upvotes: 2

Jcl
Jcl

Reputation: 28272

from o in context.Parents where o.Children.Count == 2 && o.Children.Any(x => x.Number == 0) && x.Children.Any(x => x.Number == 1) select o;

Upvotes: 0

James Manning
James Manning

Reputation: 13579

from p in context.Parents
where p.Children.Count == 2 // sounds like you can skip this one
where p.Children.Any(c => c.Number == 0)
where p.Children.Any(c => c.Number == 1)
select p;

Upvotes: 1

Related Questions