LINQ Flavored IS IN Query

There are many other questions similar to this, but none of them seem to be doing what I'm trying to do. I would like to pass a list of strings and queries

SELECT ownerid where sysid in ('', '', '') -- ie List<string> 

or how

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

I played with a.sysid.Contains (), but could not get anywhere.

+8
c # lambda linq
source share
3 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 will be better off with a HashSet<string> instead of a list, in terms of performance, considering all the availability checks. (Suppose there will be quite a few entries ... for a small number of values, this will not matter much anyway, and the List<string> may even be faster.)

Note that in the performance aspect, it is assumed that you use LINQ for objects for this - if you use something like LINQ to SQL, it does not matter, since the Contains check will not be performed in the process anyway.

+11
source share

You will not name a.sysid.Contains ; syntax for IN (SQL) is the reverse syntax for Contains (LINQ)

 var parRec = Lnq.attlnks.Where(a => chiList.Contains(a.sysid)) .Select(a => a.ownerid); 
+1
source share

In addition to the Contains approach, you can join :

 var parRec = from a in Lnq.attlnks join sysid in chiLst on a.sysid equals sysid select a.ownerid 

I'm not sure if this will be better than Contains with a HashSet, but at least it will have the same performance. This will certainly be better than using Contains with a list.

+1
source share

All Articles