What is the linq equivalent to the SQL IN operator

SqlLinqContains

Sql Problem Overview


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?

Sql Solutions


Solution 1 - Sql

.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

Solution 2 - Sql

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;

Solution 3 - Sql

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)

Solution 4 - Sql

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)));

Solution 5 - Sql

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

Solution 6 - Sql

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);

Solution 7 - Sql

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();

Solution 8 - Sql

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;

Solution 9 - Sql

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLuca RomagnoliView Question on Stackoverflow
Solution 1 - SqlDavid MortonView Answer on Stackoverflow
Solution 2 - SqlLachlan RocheView Answer on Stackoverflow
Solution 3 - SqlJustin NiessnerView Answer on Stackoverflow
Solution 4 - SqlatreeonView Answer on Stackoverflow
Solution 5 - SqlNathan TaylorView Answer on Stackoverflow
Solution 6 - SqlKamalView Answer on Stackoverflow
Solution 7 - Sqluser12063853View Answer on Stackoverflow
Solution 8 - SqlAndreyAkinshinView Answer on Stackoverflow
Solution 9 - SqlShahidView Answer on Stackoverflow