RSo*_*erg 70 c# linq asp.net linq-to-sql
我正在使用LINQ to SQL查询并遇到了一个问题,我有4个可选字段来过滤数据结果.通过可选,我的意思是可以选择输入值.具体来说,一些文本框可能有一个值或有一个空字符串和一些下拉列表可能已选择或可能没有...
例如:
using (TagsModelDataContext db = new TagsModelDataContext())
{
var query = from tags in db.TagsHeaders
where tags.CST.Equals(this.SelectedCust.CustCode.ToUpper())
&& Utility.GetDate(DateTime.Parse(this.txtOrderDateFrom.Text)) <= tags.ORDDTE
&& Utility.GetDate(DateTime.Parse(this.txtOrderDateTo.Text)) >= tags.ORDDTE
select tags;
this.Results = query.ToADOTable(rec => new object[] { query });
}
Run Code Online (Sandbox Code Playgroud)
现在我需要添加以下字段/过滤器,但前提是它们是由用户提供的.
我已经拥有的查询工作得很好,但要完成该功能,需要能够在where子句中添加这4个其他项,只是不知道如何!
and*_*eer 121
您可以编写原始查询的代码:
var query = from tags in db.TagsHeaders
where tags.CST.Equals(this.SelectedCust.CustCode.ToUpper())
&& Utility.GetDate(DateTime.Parse(this.txtOrderDateFrom.Text)) <= tags.ORDDTE
&& Utility.GetDate(DateTime.Parse(this.txtOrderDateTo.Text)) >= tags.ORDDTE
select tags;
Run Code Online (Sandbox Code Playgroud)
然后根据条件,添加额外的约束条件.
if(condition)
query = query.Where(i => i.PONumber == "ABC");
Run Code Online (Sandbox Code Playgroud)
我不知道如何使用查询语法对此进行编码,但id确实可以使用lambda.也适用于初始查询的查询语法和辅助过滤器的lambda.
您还可以包含一段扩展方法(下面),我将其编码了一段时间以包含条件where语句.(与查询语法不兼容):
var query = db.TagsHeaders
.Where(tags => tags.CST.Equals(this.SelectedCust.CustCode.ToUpper()))
.Where(tags => Utility.GetDate(DateTime.Parse(this.txtOrderDateFrom.Text)) <= tags.ORDDTE)
.Where(tags => Utility.GetDate(DateTime.Parse(this.txtOrderDateTo.Text)) >= tags.ORDDTE)
.WhereIf(condition1, tags => tags.PONumber == "ABC")
.WhereIf(condition2, tags => tags.XYZ > 123);
Run Code Online (Sandbox Code Playgroud)
扩展方法:
public static IQueryable<TSource> WhereIf<TSource>(
this IQueryable<TSource> source, bool condition,
Expression<Func<TSource, bool>> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
Run Code Online (Sandbox Code Playgroud)
这是IEnumerables的相同扩展方法:
public static IEnumerable<TSource> WhereIf<TSource>(
this IEnumerable<TSource> source, bool condition,
Func<TSource, bool> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
Run Code Online (Sandbox Code Playgroud)
Cod*_*ick 31
只需要对参数的存在使用条件检查.例如:
where (string.IsNullOrEmpty(ProductNumber) || ProductNumber == tags.productNumber)
Run Code Online (Sandbox Code Playgroud)
这样,如果未输入产品编号,则表达式将在所有情况下返回true,但如果输入,则仅在匹配时返回true.
| 归档时间: |
|
| 查看次数: |
86392 次 |
| 最近记录: |