Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Select Where IN

Tags:

c#

sql

lambda

linq

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.

like image 616
Volearix Avatar asked Mar 26 '26 01:03

Volearix


1 Answers

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.

like image 150
Sergey Berezovskiy Avatar answered Mar 28 '26 15:03

Sergey Berezovskiy