Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ flavored IS IN Query

Tags:

c#

lambda

linq

There are quite a few other questions similiar to this but none of them seem to do what I'm trying to do. I'd like pass in a list of string and query

SELECT ownerid where sysid in ('', '', '') -- i.e. List<string>

or like

var chiLst = new List<string>();
var parRec = Lnq.attlnks.Where(a => a.sysid IN chiList).Select(a => a.ownerid);

I've been playing around with a.sysid.Contains() but haven't been able to get anywhere.

like image 460
bumble_bee_tuna Avatar asked Apr 16 '12 18:04

bumble_bee_tuna


2 Answers

Contains is the way forward:

var chiLst = new List<string>();
var parRec = Lnq.attlnks.Where(a => chiList.Contains(a.sysid))
                        .Select(a => a.ownerid);

Although you'd be better off with a HashSet<string> instead of a list, in terms of performance, given all the contains checks. (That's assuming there will be quite a few entries... for a small number of values, it won't make much difference either way, and a List<string> may even be faster.)

Note that the performance aspect is assuming you're using LINQ to Objects for this - if you're using something like LINQ to SQL, it won't matter as the Contains check won't be done in-process anyway.

like image 173
Jon Skeet Avatar answered Sep 28 '22 01:09

Jon Skeet


You wouldn't call a.sysid.Contains; the syntax for IN (SQL) is the reverse of the syntax for Contains (LINQ)

var parRec = Lnq.attlnks.Where(a => chiList.Contains(a.sysid))
                        .Select(a => a.ownerid);
like image 33
Adam Robinson Avatar answered Sep 28 '22 03:09

Adam Robinson