动态 LINQ 查询

本文关键字:查询 LINQ 动态 | 更新日期: 2023-09-27 18:35:39

如果我有具有属性 Id、标题、ISBN、标签的书籍实体。在wform窗口中,用户可以输入搜索文本,并从组合框中选择ByTitle,ByISBN,ByTag搜索选项。

在按钮单击事件中,这些值被视为

var comboSelection = (comboBox1.SelectedItem ?? "").ToString();
var searchText = txtSearchText.Text;

现在我想使用这些值从我的存储库中获取值。我已经有存储库了。GetBooks() 返回 IEnumerable of books。

我的问题是如何定义带有 where 子句的查询,并考虑到组合选择。

var result = repository.GetBooks().Where(x=>x. ....)

显然,如果选择了 ByTag,则应.Where(x=>x.Tag==comboSelection)此查询

动态 LINQ 查询

我想你的ComboBox有这些项目:ByTitleByISBNByTag。您应该执行以下操作:

//Use this Dictionary to get the corresponding delegate for the Where method
//Suppose your GetBooks() returns a collection of Book elements
Dictionary<Func<Book,bool>> predicates = new Dictionary<Func<Book,bool>>();
predicates.Add("ByTitle", b=>b.Title.Contains(searchText));
predicates.Add("ByISBN", b=>b.ISBN.Contains(searchText));
predicates.Add("ByTag", b=>b.Tag.Contains(searchText));
if(comboSelection != ""){
  var result = repository.GetBooks().Where(predicates[comboSelection]);
  //... other code
}

注意:其他方法:

  • 使用 Reflection ,但是您的ComboBox items应与相应的Property name相关联。
  • 使用 Dynamic LINQ ,您应该搜索更多相关信息。

可以使用动态 Linq 库。之后你可以写一些这样的东西

repository.GetBooks().Where("Tag == @0", comboSelection);