开发者

lambda expression for exists within list

开发者 https://www.devze.com 2023-01-06 04:21 出处:网络
If I want to filter a list of objects against a specific id, I can do this: list.Where(r => r.Id == idToCompare);

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 a开发者_Go百科gainst?

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

int[] listofIds = GetListofIds();

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


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));


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));


You can use the Contains() extension method:

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


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消