Aeseir
Aeseir

Reputation: 8434

LINQ get find all with id in list

I am trying to figure out non query way to do return a list of all objects if their ID is in test list. Example below:

Hero - table
Columns: id = INT , name = STRING, age = INT, power = INT;

var testList = {1,2,3};
var secondArray = {};

foreach (var id in testList )
{
    // check if ID in database
    var item = db.Hero.ToList().Find(o => o.Id = id);
    if( item != null)
    {
       secondArray.push(item);
    }
}

Now i have seen this whole thing done in single line but cannot remember how it was done.

The result i am after is List of all objects containing that have ids 1,2,3.

Upvotes: 4

Views: 20116

Answers (2)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48600

How about

var result = db.Hero.Where(x => testList.Contains(x.Id));

This would hit DB just once instead of 3 times.

Upvotes: 4

Ofir Winegarten
Ofir Winegarten

Reputation: 9365

You have to use Contains on testList:

var secondArray= db.Hero.Where (h=> testList.Contains(h.Id))

Upvotes: 14

Related Questions