Archive

You are currently browsing the Log et al – Peter Curd blog archives for October, 2012.

Oct

20

How to perform an SQL “IN” query in Linq

By pcurd

Using Linq to achieve a query that in SQL that uses the “IN” keyword – i.e. to check a value against a range of values – requires use of the .Contains method on a new array of the range of values.

For example, if I need to exclude from reports the following customers:

  1. Internal
  2. Demo
  3. Sample
I would in SQL use something like:
CustomerName NOT IN ('Internal', 'Demo', 'Sample')
In Linq I need something like:
!(new[] {"Internal", "Demo", "Sample"}).Contains(CustomerName))

Appropriately wired into EF or your ORM of choice.

I think this is confusing since it is written backwards to a SQL programmer, so it reads “does this list of things contain the value?” instead of “is the value in this list of things?” as we are used to in SQL.