3

I have a comma-separated list of record Ids that I get from a query string. I need to return all the records (from a SQL Server database) with those Ids. What's the best way to do that in Linq?

I figure that it will ultimately be transformed into a SQL statement of the form "WHERE id IN (1,2,3,...)", and since that query contains the same comma-separated list that I'm starting with, it seems a shame to un-pack it into an int array and then let Linq convert it back again. But if that's the only way, then fine.

Gary McGill
  • 26,400
  • 25
  • 118
  • 202

2 Answers2

6

As you hinted at, it's easiest to convert it to an array first.

string csv = "1,2,3";
IEnumerable<int> ids = csv.Split(',').Select( str => int.Parse(str));

var records = db.Records.Where( rec => ids.Contains(rec.id) );
James
  • 2,445
  • 2
  • 25
  • 35
1

Use Dynamic Linq to avoid the unnecesary conversion

.Where("MyColumn.Contains(@0)", myArray)

Dynamic Linq - String.Split

How to use "contains" or "like" in a dynamic linq query?

Community
  • 1
  • 1
The Internet
  • 7,959
  • 10
  • 54
  • 89