LinQ select in / contains

13/04/2010

You have a large set of data and is only interested in a subset of it. But the subset is not easily defined, it could be a list of IDs or something similar what do you do?
In SQL you could write a

SELECT * FROM Items WHERE itemId IN (1, 2, 3)

To do something similar with LinQ you could write:

List ids = new List
{1,2};
List Items = new List {
new Item {
itemId = 2,
description = "Toy"
},
new Item {
itemId = 13,
description = "Gun"
}};

var output = from i in Items
where ids.Contains(i.itemId)
select i;

This will only return the items which itemid is found in the ids list, and actually it will be translated to SQL similar to the select statement above, thus it will utilize the power of your database engine.