tags:

views:

98

answers:

4

if i want to filter a list of object 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");   
+5  A: 

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 Dictionary.

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

You can use the Contains() extension method:

list.Where(r => listofIds.Contains(r.Id))
Shirik
+4  A: 
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));
Anthony Pegram
Used with Entity framework (and possibly LINQ-To-SQL), this will actually translate into "SELECT * FROM Table where Id in (1,2,3,4)", resulting in only one trip to the server.
Igor Zevaka
+1  A: 

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);
TheEvilPenguin
I was about to post the same answer (though using the extension method syntax, but that's simply personal preference). And yes, `join` is more optimized than `Contains`, as it constructs an in-memory hash table of the keys on both sides rather than doing a sequential search in `listOfIds` for every member of `list`.
Adam Robinson
@Anthony Pegram: Thanks, I just figured it out and deleted my comment, sorry.For reference, I said I couldn't figure out the syntax and asked for help
TheEvilPenguin