Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

c# - IQueryable where clause checking dynamic array

I need to know what I need to place for a where clause to filter for a dynamic list of integers.

I've been trying to search for this using IQueryable and 'where in array', but I do not know the terms I need to search it any better. I've been very bad and looking over code made by another person and copying patterns instead of learning what's going on.. And I just can't figure this out.

In the line of my csharp code I'm working on, I am trying to mimic the filter as from an SQL query where it would look like the following, (to grab the data from the table jobs with id =1, id=2, and id=3).

SELECT * FROM jobs j WHERE j.id in (1,2,3)

Where the table jobs might look like:

CREATE TABLE jobs
{   id       [int] identity(1,1) not null,
    username [varchar](50) not null,
    category [varchar](50) not null,
    ...
}

What I have so far:

string csv_ids = "1,2,3";


IQueryable<MyClass> info = null;
info = from j in db.jobs

       // this is the line I'm having trouble with
       where j.id in csv_ids.Split(',') 

       select new MyClass
       {
           // getting data
       };

Solution: With Roy's help, I managed to head in the right direction, by adding

int[] ids = csv_ids.Split(',').Select(int.Parse).ToArray(); //since id is integer

and, mainly

...
// here
where ids.Contains(j.id) 
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use contains for check from list of elements

string csv_ids = "1,2,3";
string[] ids = csv_ids.Split(',');

var info = from j in db.jobs
       where ids.Contains(j.id)
       select new MyClass
       {};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...