Robbie Mills
Robbie Mills

Reputation: 2945

Efficient linq query to return objects when you have a list of object id's

I have a List of all my peronIDs and I'd like to run a Linq query that retrieves the remaining details.

This is my code, but I believe that it checks every item in my People db table against every item in my personID's list which is inefficient:

List<int> personIDs = Session["PeopleList"] as List<int>;

var people = (from c in db.People
    where (
    from a in personIDs
    where a == c.PersonID
    select a
    ).Any()
    select c);

Is there a more efficient way to run this code?

Upvotes: 1

Views: 162

Answers (1)

Diana Nassar
Diana Nassar

Reputation: 2303

You can do it this way:

var people = (from c in db.People
              where personIDs.contains(c.id)
              select c).ToList();

Upvotes: 3

Related Questions