我有一系列具有各种属性(标题,发行年份,评级等)的电影,我需要使用LINQ查询进行搜索,如下所示:
public BindingList<Movie> SearchByTitle(string title)
{
var matches = from movies in movieCollection
where movies.Title == title
select movies;
// do some other stuff with the matches
}
Run Code Online (Sandbox Code Playgroud)
但我不想要一个单独的方法来搜索每个属性,因为搜索之间唯一的变化就是where节.例如where movies.Rating == rating或where movies.ReleaseYear == releaseYear.如何通过传递某种类型Expression或Func作为where节来使搜索方法可以重复用于所有不同类型的搜索?
如何通过传递某种Expression或Func作为where部分,使搜索方法可以重用于所有不同类型的搜索?
您的查询真的是没有什么比where子句等.但是你可以轻松地将where部分配置为...只是不使用查询表达式.
public BindingList<Movie> SearchByTitle(Expression<Func<Movie, bool>> predicate)
{
var matches = movies.Where(predicate);
// Do common stuff with the matches.
}
Run Code Online (Sandbox Code Playgroud)
编辑:我假设那movies是一个IQueryable<T>,因为你在谈论Expression.如果它只是一个IEnumerable<T>,你想要:
public BindingList<Movie> SearchByTitle(Func<Movie, bool> predicate)
{
var matches = movies.Where(predicate);
// Do common stuff with the matches.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1047 次 |
| 最近记录: |