我想做一个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
我怎样才能实现它?
答案 0 :(得分:4)
查询构建器的查询表达式似乎过于复杂。
我会将这些代码分开:
var search = Context.data;
string filter = txtKeyword.Text.Trim();
if (!string.IsNullOrEmpty(filter))
search = search.Where(a => a.Name.Contains(filter));
答案 1 :(得分:2)
var search = from a in Context.data
where string.IsNullOrWhitespace(txtKeyword.Text)
|| a.Name.Contains(txtKeyword.Text.Trim())
select a;
答案 2 :(得分:0)
var search = from a in Context.data
where txtKeyword.Text.Trim().Any()
|| a.Name.Contains(txtKeyword.Text)
select a;
答案 3 :(得分:0)
您可以在linq语句中对txtKeyword进行条件检查。 像这样的东西
var search = string.IsNullOrEmpty(txtKeyword.Text)
? (from a in Context.data
where a.Name.Contains(txtKeyword.Text.Trim())
select a)
: (from a in Context.data select a);
答案 4 :(得分:0)
var searchText = txtKeyword.Text.Trim();
var returnAll = string.IsNullOrEmpty(searchText);
var search = from a in Context.data
where returnAll || a.Name.Contains(searchText)
select a;