Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - WHERE IN query in linq

public Class SomeModel
{
   public int Id { get; set;}

   public string Name {get; set;}
}

this is the method I'm binding values to above model, it contains inline SQL Queries

Public ActionResult GetData()
{
  IEnumarable<SomeModel> alltheListValues = ....
}

using above method, I want to filter all the record that containing ids in following string.

string filterIds = "12,13,14,15"

SomeModel model class Id values are in Integer type, but I have string type id set, without going for looping this, I decided to use WHERE IN query to filter this.

since WHERE IN query we can get in Linq as contains

I wrote down follwoing function to filter values

IEnumarable<SomeModel> filterValues = GetData.Where(Id=> Id.ToString().Contains(filterIds));

but this is not selecting any value always zero filter result, how can I wrote this properly

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This could be a way to go:

string filterIds = "12,13,14,15";

//Convert filterIds string into a integers collection
var ids=filterIds.Split(',').Select(int.Parse);

IEnumarable<SomeModel> filterValues = GetData().Where(sm=> ids.Contains(sm.Id));

One thing I noticed now is the signature of your GetData method, I think what you mean is:

public IEnumarable<SomeModel> GetData()
{
  IEnumarable<SomeModel> alltheListValues = ....
  //...
  return alltheListValues;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...