Reputation: 10415
I have three tables in my database Subscriber
, Subscription
and Branch
.
Each Subscriber
can have one Subscription
in a specified Branch
.
I want to list all subscribers which have no subscription in a defined branch. For this purpose I wrote below function but I know it can be written more shortly and efficiently using LINQ operators but I have not enough knowledge to do this.
Can you change this function to a LINQ statement?
List<Subscriber> subscribersWithNoSubscriptinoInThisBranch(int branchId)
{
DbSet<Subscriber> allSubscribers = db.Subscriber;
List<Subscriber> subscribers = new List<Subscriber>();
foreach (Subscriber s in db.Subscriber)
{
ICollection<Subscription> subscriptions = s.Subscription;
if (subscriptions.Where(su => su.branchId == branchId).Count() == 0)
{
subscribers.Add(s);
}
}
return subscribers;
}
Upvotes: 0
Views: 58
Reputation: 284
I believe the following is what you want:
List<Subscriber> subscribers = allSubscribers
.Where(s => !s.Subscription.Any(su => su.branchId == branchId))
.ToList();
Upvotes: 3