Juan
Juan

Reputation: 17

Linq - check if the any of the values present in an array exists in the database table

I am exploring if there is a way to check if any of the values present in an array are present in a table without using a loop.

So even if 1 value is present in the table the method should return true, if none of the values are present then it should return the default false.

I am thinking like the below, below is not a working code just an idea.. so wanted to check if there is an efficient way to achieve this.

public bool CheckTable(string strList)
{
    bool IsPresent = False;
    String[] Arr = strList.split(',');
    foreach(string str in Arr)
    {
        var x = DBContext.TableEmployees.where(e => e.Location == str).select(e => e.Location);
        if(x == null)
        {
            isPresent = false;
        }
        else
        {
            isPresent = true;
        }
    }
}

Upvotes: 0

Views: 1845

Answers (1)

Caius Jard
Caius Jard

Reputation: 74730

Like this:

public bool CheckTable(string strList)
{
    string[] strs = strList.Split(',');
    return DBContext.TableEmployees.Any(e => strs.Contains(e.Location));
}

Take a read of https://www.microsoftpressstore.com/articles/article.aspx?p=2225065&seqNum=4 for more background on IN/EXISTS and how LINQ expressions are mapped to them.

When working with LINQ it's always wise to be mindful that if your expression can not be understood and translated completely into sql it might not run entirely at the server. Sometimes LINQ to sql will download data and rummage through it locally - the "store execution" section of https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/query-execution has some info (the whole document is worth reading, actually - deferred execution is a common gotcha too)

Upvotes: 1

Related Questions