Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IQueryable<T> filtering by a list of IDs

Tags:

c#

iqueryable

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);
        }
    }             
}
like image 757
JGilmartin Avatar asked Dec 02 '12 13:12

JGilmartin


2 Answers

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);
    }             
}
like image 154
Zbigniew Avatar answered Nov 12 '22 10:11

Zbigniew


You can use Contains

var iq = db.tblSearches.Where(x => Ids.Contains(x.seaUserId));
like image 41
Adil Avatar answered Nov 12 '22 11:11

Adil