Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda expression for exists within list

Tags:

c#

lambda

linq

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");   
like image 383
leora Avatar asked Jul 05 '10 03:07

leora


4 Answers

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));
like image 145
Alan Avatar answered Nov 14 '22 04:11

Alan


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));
like image 25
Anthony Pegram Avatar answered Nov 14 '22 03:11

Anthony Pegram


You can use the Contains() extension method:

list.Where(r => listofIds.Contains(r.Id))
like image 7
Shirik Avatar answered Nov 14 '22 02:11

Shirik


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);
like image 2
TheEvilPenguin Avatar answered Nov 14 '22 02:11

TheEvilPenguin