IQueryable<T> filtering by a list of IDs

JGilmartin picture JGilmartin · Dec 2, 2012 · Viewed 10.9k times · Source

Let's say we have an IQueryable<T>. the Where clause can filter by single ID values, but how can I return an IQueryable based on a list of IDs?

[TestMethod]
public void TestIQueryableWithList()
{
    int ID1 = 1;
    List<int> IDs = new List<int> { 1, 3, 4, 8 };

    using (var db = new SellooEntities())            
    {
        // works fine as single value
        var iq = db.tblSearches.Where(x => x.seaUserId == ID1);

        // how can i do it to check for all the IDs ??
        foreach(int ID in IDs)
        {
            // this obviously wont work
            var iq = db.tblSearches.Where(x => x.seaUserId == ID);
        }
    }             
}

Answer

Zbigniew picture Zbigniew · Dec 2, 2012

Get data from tblSearches where seaUserId is in IDs list:

[TestMethod]
public void TestIQueryableWithList()
{
    int ID1 = 1;
    List<int> IDs = new List<int> { 1, 3, 4, 8 };

    using (var db = new SellooEntities())            
    {
        var iq = db.tblSearches.Where(x => IDs.Contains(x.seaUserId);
    }             
}