15

I have dynamic linq WHERE statement:

dataContext.Table.Where("id = 0 Or id = 1 Or id = 2 Or ...");

I want change to:

dataContext.Table.Where("id IN (0, 1, 2, ...)");

But it doesn´t work. How can I do this for better performance?

Pavel Jedlicka
  • 575
  • 2
  • 8
  • 17

3 Answers3

12

From How to use “contains” or “like” in a dynamic linq query?

//edit: this is probably broken, see below
ids = new int[] {1,2,3,4};
dataContext.Table.Where("id.Contains(@0)", ids);

Aside: It is good practice to use placeholders in dynamic linq expressions. Otherwise you may open yourself to linq injection attacks (Is Injection Possible through Dynamic LINQ?)


EDIT:

actually I think I messed this up. Unfortunately I cannot test this at the moment. But I think the correct syntax in this case should be dataContext.Table.Where("@0.Contains(id)",ids);, not the other way around, and that version does not work out-of-the-box.

See here for a way to add this functionality to dynamic link. You need to modify the library for this.

Community
  • 1
  • 1
HugoRune
  • 13,157
  • 7
  • 69
  • 144
6
var ids = new int[] {1,2,3,4};
dataContext.Table.Where(f => ids.Contains(f.id))
Candide
  • 30,469
  • 8
  • 53
  • 60
  • 2
    Thanks, I know this, but column name "id" is changing. I get this column dinamycally. So I can´t use static Linq. I have to use dynamic linq library for string where clausule as example. [Dynamic Linq](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx) – Pavel Jedlicka Apr 17 '12 at 09:46
  • 1
    @Ingenu, read the resource and you will find out what Dynamic Linq is about – Adrian Iftode Apr 17 '12 at 17:15
4

it seems that in version 1.0.4 of System.Linq.Dynamic , we can use the following syntax dataContext.Table.Where("@0.Contains(outerIt.id)",ids); as it was made and presented in the already cited blog: here

BrunoA
  • 85
  • 2
  • It seems that for string values, ids has to be a List, and **not** an array, otherwise you get the error "No 'it' is in scope" – John M Feb 10 '20 at 08:31