0

I am going to ask a very basic question and probably a repeated one but I have a bit different situation. I want to use "in" operator in Linq. I have to get all the rows from table which has Id provided by my array and returns the row if it has. How can I do it.

My array has

var aa="1091","1092","1093" and so on.

and my table uses these Ids as Primary keys .I have to get all the rows whose Id is contained in the array and I do not want to use S.P.

Sweetie
  • 1,298
  • 6
  • 24
  • 48

2 Answers2

2

You can use Enumerable.Contains,

var aa = new string[3] { "1091", "1092", "1093" };
var res = yourDataSource.Where(c => aa.Contains(c.ID));
Maarten
  • 22,527
  • 3
  • 47
  • 68
Adil
  • 146,340
  • 25
  • 209
  • 204
1

IN statements are created by using Contains in your Where call. Assuming you use integers as IDs, you could write something like this:

var myArray=new[]{1091,1092,1094};
var myEntities=from entity in myTable
               where myArray.Contains(entity.ID)
               select entity;
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • Actually I am trying something like this:: var myEntities = from entity in ObjReport where RowArray.Contains(entity.ID.ToString()) select entity; – Sweetie Apr 14 '14 at 12:21
  • I am getting null over this. – Sweetie Apr 14 '14 at 12:22
  • Actually my source in which I am searching the Records on basis of Id.Id is a int type but The Array in which I am getting the Id as strings, I am not able to get the desired results. – Sweetie Apr 14 '14 at 12:26
  • You can easily convert the strings to ints with int.Parse, eg `myStringIds.Select(s=>int.Parse(s)).ToArray()`. Adding the conversion in the LINQ statement is a bad idea because your provider may not know how to translate `ToString()` to a SQL statement. In L2S, it would try to load *everything* and then execute `ToString()` on each entity. In EF, it would flatly refuse with a compile error – Panagiotis Kanavos Apr 14 '14 at 12:36