在LINQ中查询的位置 [英] WHERE IN query in linq
问题描述
public Class SomeModel
{
public int Id { get; set;}
public string Name {get; set;}
}
这是我将值绑定到上述模型的方法,它包含内联SQL查询
this is the method I'm binding values to above model, it contains inline SQL Queries
Public ActionResult GetData()
{
IEnumarable<SomeModel> alltheListValues = ....
}
使用上述方法,我想过滤以下字符串中包含id的所有记录.
using above method, I want to filter all the record that containing ids in following string.
string filterIds = "12,13,14,15"
SomeModel模型类Id
的值是Integer类型的,但是我设置了字符串类型id,因此无需进行循环,我决定使用WHERE IN查询来对此进行过滤.
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.
由于在查询中我们可以在Linq中获得contains
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
推荐答案
这可能是一种解决方法:
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));
我现在注意到的一件事是您的GetData
方法的签名,我想您的意思是:
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;
}
这篇关于在LINQ中查询的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!