Reputation: 459
this may be a very basic question but I haven't used Linq much so do need help. I want to retrieve a list of records based on the related record count.
for example:
I have contact entity which has 1:N relationship with a 'Role' entity. I want to select contacts that have
How do I write this using Linq
from contact in context.ContactSet
where <contact.Roles has no records> -- ??
select contact;
Please help.
Upvotes: 1
Views: 534
Reputation: 1896
The following will select all contacts that have exactly 0 or 1 items in the Roles
collection. Depending on the type of collection and the data access technology the Count
property may by a method, e.g. Count()
. (Count
also has overloads so you can conditionally count items, e.g. .Count(x => x.SomeProperty && !x.SomeOtherProperty)
from contact in context.ContactSet
where contact.Roles.Count <= 1
select contact;
Upvotes: 1
Reputation: 60556
You can use the Count()
or Any()
method
Count() - Returns the number of elements in a sequence.
Any() - Determines whether any element of a sequence satisfies a condition.
Query Syntax
from contact in context.ContactSet
where contact.Roles.Count() == 0
select contact;
Method Syntax
context.ContactSet.Where(c=> c.Roles.Count() != 0));
Query Syntax
from contact in context.ContactSet
where !contact.Roles.Any()
select contact;
Method Syntax
context.ContactSet.Where(c=> !c.Roles.Any());
Upvotes: 2
Reputation: 75326
You can check by using Count() <= 1
Linq style:
from contact in context.ContactSet
where contact.Roles.Count() <= 1
select contact;
Method style:
context.ContactSet.Where(c => c.Roles.Count() <= 1);
Upvotes: 1
Reputation: 4009
To select contacts with no roles:
from contact in context.ContactSet
where !contact.Roles.Any()
select contact;
or simply:
context.ContactSet.Where(c=> !c.Roles.Any());
To select contacts with n roles assigned:
from contact in context.ContactSet
where contact.Roles.Count()==n
select contact;
or simply:
context.ContactSet.Where(c=> c.Roles.Count()==n));
Upvotes: 1