8

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.

bumble_bee_tuna
  • 3,533
  • 7
  • 43
  • 83

3 Answers3

11

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

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);
Adam Robinson
  • 182,639
  • 35
  • 285
  • 343
1

In addition to the Contains approach, you could join:

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

I'm not sure whether this will do better than Contains with a HashSet, but it will at least have similar performance. It will certainly do better than using Contains with a list.

phoog
  • 42,068
  • 6
  • 79
  • 117
  • Assuming LINQ to Objects, it will basically build a `HashSet` within the join implementation. (And it will be faster than a `List` *if the list grows large* - if the list is very short, then a hash-based implementation could be slower, as it needs to generate the hash of the target first. There are all kinds of variables in play, really.) – Jon Skeet Apr 16 '12 at 18:31