Volearix
Volearix

Reputation: 1593

Linq Select Where IN

Cannot find the lambda linq equivalent to SELECT * FROM [Source] WHERE [Field] IN [String Array]. I need to select all data from a data table that contains zip codes from a string array. I would like a faster way than just iterating through every row comparing them as I believe this would be fairly inefficient (or I believe it would anyway). I can't seem to find an adequate answer on Google of how to perform a lambda LINQ IN query on a data table. Any assistance would be great! Here is what I have currently:

List<string> lst = dtEtechZipCodeEmailRecipients.AsEnumerable()
                .Select(o => o.Field<string>("Email")).Distinct().ToList();
for (int i = 0; i < lst.Count - 1; ++i)
{
    string email = lst[i].ToString().ToUpper();
    string[] zipCodes = dtEtechZipCodeEmailRecipients.AsEnumerable()
        .Where(zip => (zip.Field<string>("Email") ?? (object)String.Empty).ToString().ToUpper() == email)
        .Select(zip => zip.Field<string>("ZipCode")).ToArray();

    Console.WriteLine(" - " + email);

    dtEtechModelRequests.AsEnumerable().Where(mod => mod.Field<string>("ZipCode").Contains(zipCodes)).Select(mod => mod);
}

That does not work, everything but the .Contains does do exactly what I need though. I left the .Contains to try and demonstrate my point.

Upvotes: 3

Views: 805

Answers (2)

Krishanu Dey
Krishanu Dey

Reputation: 6406

Simple answer to your question is,

[Source].Where(el => [String Array].Contains(el.Field<string>("Field"))

And if you need NOT IN then follow the following pattern

Adding ! infront of your [String Array]

[Source].Where(el => ![String Array].Contains(el.Field<string>("Field"))

alternative representation

[Source].Where(el => [String Array].Contains(el.Field<string>("Field")==false)

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

You should do opposite thing - check whether array of zip codes contains current zip code:

Where(mod => zipCodes.Contains(mod.Field<string>("ZipCode"))

That is same as verifying if current zip code IN array.

Upvotes: 2

Related Questions