views:

53

answers:

3

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

+1  A: 
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;
James Manning
I think the answer is close. This would return cases where both children have number of 0 or 1
jdelator
This answer works because there's 2 children - the 2nd 'where' makes sure at least one child has Number == 0, and the 3rd 'where' makes sure at least one child has Number == 1. Since those 2 obviously can't be the same child, and since there's only 2 children, it must be the correct parent.
James Manning
You are correct. Thanks
jdelator
A: 
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;
Jcl
at least at first glance, this looks like the same answer I gave - am I missing something?
James Manning
sorry about that, I missed your answer, you are right
Jcl
+1  A: 

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));
wcm