Menu Home

LinQ select in / contains

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<int> ids = new List<int>
{1,2};
List<Item> Items = new List<Item> {
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.

Categories: Uncategorized

Tagged as:

Simon J.K. Pedersen

Leave a Reply

Your email address will not be published. Required fields are marked *