c# - LINQ 按文本搜索

标签 c# linq

我想做一个 linq, "当txtKeyword.Text为空时,查询将返回所有数据,否则返回包含txtKeyword.Text的数据。"

        var search = from a in Context.data
                     where txtKeyword.Text.Trim().Count() > 0 ? a.Name.Contains(txtKeyword.Text.Trim()) : true
                     select a;

Error:
DbExpressionBinding requires an input expression with a collection ResultType.
Parameter name: input

我怎样才能实现它?

最佳答案

对于查询构建器来说,查询表达式似乎太复杂了。

我会像这样分离代码:

var search = Context.data;
string filter = txtKeyword.Text.Trim();
if (!string.IsNullOrEmpty(filter))
    search = search.Where(a => a.Name.Contains(filter));

关于c# - LINQ 按文本搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34209457/

相关文章:

c# - 如何在将数据从 Dataset 导出到 Excel 后下载 excel 文件?

C#:在 Word 中打开 FileStream 中的 Word 文件以供读取

c# - LINQ OrderByDescending 到 OrderByAscending?

c# - 根据属性的最小值从集合中查找项目

c# - 基于 bool 值重新使用 LINQ 查询

c# - StreamReader 不读取回车符

c# - ViewBag 属性已设置但不可访问

c# - 查找两个嵌套字典之间的差异

c# - Linq Distinct 没有带回正确的结果

c# - 使用 DataTemplate 在 WPF 中通过 LINQ to SQL 绑定(bind) ListBox 的 ListItem 属性的两种方式