0

In my program i have a database with a table containing persons.

Every person has a collection of clothes, which has a collection of fabrics. Say i want to return the number of persons who has clothes that contain cotton.

I only want to count them once even if the person has more than one clothes that contain cotton.

I tried the following and several other solutions but it didn't quite work out for me:

if ((from p in context.Persons
    from c in p.Clothes
    from f in c.Fabrics
    select f.Name == "Cotton").Count();
{ 
CodeProg
  • 131
  • 12

1 Answers1

4
var count = database.People
    .Where(p => p.Clothes.Any(c => c.Fabrics.Any(f => f.Name == "Cotton")))
    .Count();

Select all people where any of the clothes' fabrics are Cotton.

Sam Axe
  • 33,313
  • 9
  • 55
  • 89
  • You could also change `Where` to `Count` in your code above. – Igor May 11 '18 at 19:29
  • Seems to work! Thanks a lot! Could you maybe elaborate on what the arrow means? – CodeProg May 11 '18 at 19:30
  • 3
    @CodeProg - see [C# Lambda expressions: Why should I use them?](https://stackoverflow.com/questions/167343/) and [What does this C# code with an “arrow” mean and how is it called?](https://stackoverflow.com/q/4829054/1260204) – Igor May 11 '18 at 19:31