tags:

views:

167

answers:

6

With linq i have to check if a value of a row is present in a array.
The equivalent of the sql query:

WHERE ID IN (2,3,4,5)

How can i do?

thanks

+7  A: 

.Contains

var resultset = from x in collection where new[] {2,3,4,5}.Contains(x) select x

Of course, with your simple problem, you could have something like:

var resultset = from x in collection where x >= 2 && x <= 5 select x
David Morton
+2  A: 

An IEnumerable<T>.Contains(T) statement should do what you're looking for.

Nathan Taylor
+2  A: 
db.SomeTable.Where(x => new[] {2,3,4,5}.Contains(x));

or

from x in db.SomeTable
where new[] {2,3,4,5}.Contains(x)
Justin Niessner
+3  A: 

Perform the equivalent of an SQL IN with IEnumerable.Contains().

var idlist = new int[] { 2, 3, 4, 5 };

var result = from x in source
          where idlist.Contains(x.Id)
          select x;
Lachlan Roche
+1  A: 

A very basic example using .Contains()

List<int> list = new List<int>();
for (int k = 1; k < 10; k++)
{
    list.Add(k);
}

int[] conditionList = new int[]{2,3,4};

var a = (from test in list
         where conditionList.Contains(test)
         select test);
Kamal
You could clean this up a lot by changing your `for` loop to `IEnumerable<int> list = Enumerable.Range(1, 10);`
Justin Niessner
Point taken. +1 But to be fair, I was just writing code I knew would work without needing to test it :)
Kamal
+1  A: 

You can write help-method:

    public bool Contains(int x, params int[] set) {
        return set.Contains(x);
    }

and use short code:

    var resultset = from x in collection
                    where Contains(x, 2, 3, 4, 5)
                    select x;
DreamWalker