0

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;
}
2
  • 1
    How did you identify if above code is less efficient compared to a LINQ one? Commented Mar 2, 2020 at 13:07
  • 2
    @Lucifer This does one query for all subscribers, then does one query for each subscriber to get the count of subscriptions which is way less efficient than one query to do all of it on the DB. Commented Mar 2, 2020 at 13:14

1 Answer 1

3

I believe the following is what you want:

List<Subscriber> subscribers = allSubscribers
    .Where(s => !s.Subscription.Any(su => su.branchId == branchId))
    .ToList();
Sign up to request clarification or add additional context in comments.

4 Comments

It depends on what you want to achieve. If you're not done with filtering yet you should not take the results in memory with a ToList. If this is the final result then yes add a ToList
This one lists all subscribers which have subscription in specified branch. I want those who have not subscriptions.
I think OP wants the inverse of that, "subscribers which have no subscription in a defined branch"
I will change it to !s.Subscription.Any(..)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.