如何过滤LINQ查询。在ListBox控件中显示结果

时间:2015-07-11 22:39:31

标签: c# linq

我希望根据用户输入将查询过滤到文本框中,并在列表框中显示结果。我知道可以做到,但我似乎无法找到正确的方向。以下是我想要过滤的查询示例:

var q2 = from o in db.Orders
                 orderby o.OrderDate descending
                 join c in db.Customers on o.CustomerID equals c.CustomerID
                 select new { Customer = c.ContactName, orderDate = o.OrderDate, orderID = o.OrderID };

我希望能够说出过滤OrderID或说ContactName。我只是学习所以请保持温柔,但任何帮助都将不胜感激!如果我的解释不够好,这里的快照也有帮助。

Filter using text box located in the search tab header.

好的,我从安德里得到了这个!它是一个开始,但不知道在实际过滤方面去哪里。

`var q2 = from o in db.Orders
                     orderby o.OrderDate descending
                     join c in db.Customers on o.CustomerID equals c.CustomerID
                     select new { Customer = c.ContactName, orderDate = o.OrderDate, orderID = o.OrderID };

            if (tbxSearch.Text != null)
            {
                q2 = q2.Where();
            }

            lbxQ2.ItemsSource = q2;`

1 个答案:

答案 0 :(得分:1)

您正在寻找where条款。

如果您从输入中知道应该过滤哪个字段(动态字段过滤要复杂得多),您可以按照以下几点做一些事情:

var q2 = from o in db.Orders
             orderby o.OrderDate descending
             join c in db.Customers on o.CustomerID equals c.CustomerID
             select new { Customer = c.ContactName, orderDate = o.OrderDate, orderID = o.OrderID };

if (customer name filter is not empty)
{
    q2 = q2.Where(x => x.Customer == <customer name filter value>);
}

if (order id filter is not empty)
{
    q2 = q2.Where(x => x.OrderID == <order id filter value>);
}

当然上面只是一个显示基本想法的伪代码,你应该根据你的要求实际应用过滤器。