What is the linq equivalent to the SQL IN operator
Asked Answered
E

9

64

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

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

How can I do it?

Emmaemmalee answered 25/2, 2010 at 13:43 Comment(0)
E
60

.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
Eva answered 25/2, 2010 at 13:45 Comment(2)
I'm getting the error: int[] does not contain a definition of contains.Imperfect
Could be because System.Linq not included ?Gerous
S
31

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;
Spree answered 25/2, 2010 at 13:48 Comment(0)
C
12
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)
Cede answered 25/2, 2010 at 13:47 Comment(1)
shouldn't it be using x.<propertyname> that matches with the datatype to search, in this case, integers. like db.sometable.where(x => new[] {1,2}.Contains(x.Id));Wadley
R
11

Intersect and Except are a little more concise and will probably be a bit faster too.

IN

collection.Intersect(new[] {2,3,4,5});

NOT IN

collection.Except(new[] {2,3,4,5});

or

Method syntax for IN

collection.Where(x => new[] {2,3,4,5}.Contains(x));

and NOT IN

collection.Where(x => !(new[] {2,3,4,5}.Contains(x)));
Radloff answered 11/7, 2014 at 10:17 Comment(0)
P
3

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

Pah answered 25/2, 2010 at 13:46 Comment(0)
M
2

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);
Muddlehead answered 25/2, 2010 at 13:52 Comment(2)
You could clean this up a lot by changing your for loop to IEnumerable<int> list = Enumerable.Range(1, 10);Cede
Point taken. +1 But to be fair, I was just writing code I knew would work without needing to test it :)Muddlehead
C
2

The above situations work when the Contains function is used against primitives, but what if you are dealing with objects (e.g. myListOrArrayOfObjs.Contains(efObj))?

I found a solution! Convert your efObj into a string, thats separated by _ for each field (you can almost think of it as a CSV representation of your obj)

An example of such may look like this:

     var reqAssetsDataStringRep = new List<string>();

        foreach (var ra in onDemandQueueJobRequest.RequestedAssets)
        {
            reqAssetsDataStringRep.Add(ra.RequestedAssetId + "_" + ra.ImageId);
        }

        var requestedAssets = await (from reqAsset in DbContext.RequestedAssets
                                     join image in DbContext.Images on reqAsset.ImageId equals image.Id
                                     where reqAssetsDataStringRep.Contains(reqAsset.Id + "_" + image.Id)
                                     select reqAsset
                                           ).ToListAsync();
Countermove answered 13/9, 2019 at 15:3 Comment(0)
V
1

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;
Verge answered 25/2, 2010 at 13:53 Comment(0)
C
-1

Following is a generic extension method that can be used to search a value within a list of values:

public static bool In<T>(this T searchValue, params T[] valuesToSearch)
{
    if (valuesToSearch == null)
        return false;
    for (int i = 0; i < valuesToSearch.Length; i++)
        if (searchValue.Equals(valuesToSearch[i]))
            return true;

    return false;
}

This can be used as:

int i = 5;
i.In(45, 44, 5, 234); // Returns true

string s = "test";
s.In("aa", "b", "c"); // Returns false

This is handy in conditional statements.

Cadwell answered 6/3, 2015 at 6:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.