-1

I'm attempting to use a linq query to dynamically select records based on account id. account id is a int column in sql server.

var idList = new int[123, 456];   //these number change with each user.
foreach (var id in idList) {
      query = query.WHERE(cs => cs.pkID = id);
}

The above makes it a AND where clause. I'd rather have it be an OR. The above idList can contain 1 to 100. Varying with each user.

How can I make linq work with a OR clause. Contains doesn't work on INT columns.

Would like the select to look something like this.

 select * from table where id = 123 or id = 456

I have a bunch of other columns that could be appended to the where clause. Getting a dynamic OR working is giving me a headache.

Thanks.

2 Answers2

3

You can use cs=>idList.Contains(cs.pkID)

var idList = new List<int>(){123, 456};   
var result = query.Where(cs => idList.Contains(cs.pkID));

This way you don't need any loop and it is equivalent to:

SELECT somecolumns FROM sometable WHERE pkId in (123, 456)

In your case, using Contains, makes more sense than creating dynamic where clause with OR.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
0
query = query.WHERE(cs => idList.Contains(cs.pkID);

You can use something like that.

Watch our with your original query: = is not == in C#.

Carra
  • 17,808
  • 7
  • 62
  • 75