我所拥有的是从查询字符串(例如 23、51、6、87、29)接收到的一串逗号分隔的 ID。或者,该字符串可以只说“全部”。
在我的 Linq 查询中,我需要一种说法(在伪代码中):
from l in List<>
where l.Id = all_of_the_ids_in_csv
&& other conditions
select new {...}
我只是不知道该怎么做。我什至不确定用谷歌搜索什么来让我朝着正确的方向前进。任何指向正确方向的东西都会非常有帮助。
我所拥有的是从查询字符串(例如 23、51、6、87、29)接收到的一串逗号分隔的 ID。或者,该字符串可以只说“全部”。
在我的 Linq 查询中,我需要一种说法(在伪代码中):
from l in List<>
where l.Id = all_of_the_ids_in_csv
&& other conditions
select new {...}
我只是不知道该怎么做。我什至不确定用谷歌搜索什么来让我朝着正确的方向前进。任何指向正确方向的东西都会非常有帮助。
我建议将您的查询分成两部分 - 第一部分将按 ID 选择,而选择的部分将选择其他条件。
首先:检查查询字符串是否包含数字,或者只是all:
var IEnumerable<ListItemType> query = sourceList;
if(queryStringValue != "All")
{
var ids = queryStringValue.Split(new[] { ',' })
.Select(x => int.Parse(x)) // remove that line id item.Id is a string
.ToArray();
query = query.Where(item => ids.Contains(item.Id));
}
from l in query
// other conditions
select new {...}
因为 LINQ 查询延迟执行,您可以构建这样的查询而不会降低性能。ToList在您要求结果(通过调用或枚举)之前,不会执行查询。
如果您真的只需要一个 LINQ 查询:
var idArray = all_of_the_ids_in_csv.Split(',');
from l in List<>
where (all_of_the_ids_in_csv == "All" || idArray.Contains(l.Id))
&& other conditions
select new {...}
诀窍是使用string.Split
var ids = string.split(rawIdString, ",").ToList();
var objects = ids.Where(id=> /*filter id here */).Select(id=>new { /* id will be the single id from the csv */ });
// at this point objects will be an IEnumerable<T> where T is whatever type you created in the new statement above