leora
leora

Reputation: 196499

lambda expression for exists within list

If I want to filter a list of objects against a specific id, I can do this:

list.Where(r => r.Id == idToCompare);   

What if, instead of a single idToCompare, I have a list of Ids to compare against?

What is the syntax for comparing against a predefined list? Something like:

int[] listofIds = GetListofIds();

list.Where(r => r.Id "in listofIds");   

Upvotes: 44

Views: 133565

Answers (4)

Alan
Alan

Reputation: 46823

If listOfIds is a list, this will work, but, List.Contains() is a linear search, so this isn't terribly efficient.

You're better off storing the ids you want to look up into a container that is suited for searching, like Set.

List<int> listOfIds = new List(GetListOfIds());
lists.Where(r=>listOfIds.Contains(r.Id));

Upvotes: 73

TheEvilPenguin
TheEvilPenguin

Reputation: 5682

I would look at the Join operator:

from r in list join i in listofIds on r.Id equals i select r

I'm not sure how this would be optimized over the Contains methods, but at least it gives the compiler a better idea of what you're trying to do. It's also sematically closer to what you're trying to achieve.

Edit: Extension method syntax for completeness (now that I've figured it out):

var results = listofIds.Join(list, i => i, r => r.Id, (i, r) => r);

Upvotes: 2

Anthony Pegram
Anthony Pegram

Reputation: 126854

var query = list.Where(r => listofIds.Any(id => id == r.Id));

Another approach, useful if the listOfIds array is large:

HashSet<int> hash = new HashSet<int>(listofIds);
var query = list.Where(r => hash.Contains(r.Id));

Upvotes: 26

Shirik
Shirik

Reputation: 3701

You can use the Contains() extension method:

list.Where(r => listofIds.Contains(r.Id))

Upvotes: 7

Related Questions