C#Linq where子句

Mic*_*eal 3 c# linq variables list where-clause

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

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

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

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

有一种方法可以传递LINQ查询中where子句中内置的变量吗?

 Stemp = (from s in SList
               where ***query***
               orderby s.DataScadenza
               select s).ToList();
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 6

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

    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();
Run Code Online (Sandbox Code Playgroud)