【问题标题】:C# Linq where clauseC# Linq where 子句
【发布时间】:2016-12-14 12:38:07
【问题描述】:

我正在尝试创建一个 linq 查询 where 子句是基于用户选择的构造变量

if (!string.IsNullOrEmpty(txbbox.Text)) 
{

  query = "s.date== DateTime.Parse(txbbox.Text)";
}

if (!string.IsNullOrEmpty(txbbox.Text))
{
   query = query + " & (s.type.Contains(txbbox.Text))";
}

有没有办法在 LINQ 查询中传递 where 子句中内置的变量?

 Stemp = (from s in SList
               where ***query***
               orderby s.DataScadenza
               select s).ToList();

【问题讨论】:

  • @HimBromBeere 这里不需要使用字符串,所以我认为这不适用
  • 注意:你从同一个文本框中读取了两次并应用了完全不兼容的测试......这几乎肯定是一个错误

标签: c# linq list variables where-clause


【解决方案1】:

是的;在这种情况下非常简单,实际上:

    IEnumerable<Whatever> query = SList; // avoid var here, as will impact later assignment
    if (!string.IsNullOrEmpty(txbbox.Text)) 
    {
        var when = DateTime.Parse(txbbox.Text); // to avoid parsing per item
        query = query.Where(s => s.date == when);
    }
    if (!string.IsNullOrEmpty(txbbox.Text))
    {
        query = query.Where(s => s.type.Contains(txbbox.Text));
    }
    Stemp = query.OrderBy(s => s.DateScadenze).ToList();

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多