【问题标题】:Reduce linq query for filtering减少用于过滤的 linq 查询
【发布时间】:2014-06-05 11:12:32
【问题描述】:

我有一个视图,其中包含 3 个文本框,它们绑定到 ViewModel SupplierNameContactAddress 中的属性和一个绑定到我的 ViewModel 中 SearchCommand 属性的按钮。

我的要求是根据上述属性过滤Supplier 记录。我使用了 EntityFramework。

用户可以输入任何上述文本框,这会导致我编写 9 个不同的查询。 例如,如果用户仅在 SupplierName 文本框上输入数据,那么我需要以 SupplierName 作为参数运行一个查询。如果用户输入 SupplierNameContact 文本框,那么我需要运行另一个查询。以此类推。

这是我的代码:

public IEnumerable<Model.Supplier> GetAllSuppliersBySearch(string nameMatch, string contactMatch, string phoneMatch)
    {

        if(nameMatch!=null)
        {
             var q = from f in Context.Suppliers
                where f.SupplierName==nameMatch 
                select f;
        }
        else if(contactMatch!=null)
        {
             var q = from f in Context.Suppliers
                where  f.ContactName==contactMatch 
                select f;
        }
        else if(phoneMatch!=null)
        {
            var q = from f in Context.Suppliers
                where  f.ContactName==contactMatch 
                select f;
        }

        return q.AsEnumerable();
    }

如何用一个查询或以任何优化的方式来完成此任务,而不是编写多个查询?

【问题讨论】:

    标签: c# sql wpf linq entity-framework


    【解决方案1】:

    使用 lambda 语法编写查询:

    IQueryable<Supplier> query = Context.Suppliers;
    
    if (!String.IsNullOrEmpty(nameMatch))
       query = query.Where(s => s.SupplierName == nameMatch);
    
    if (!String.IsNullOrEmpty(contactMatch))
       query = query.Where(s => s.ContactName == contactMatch);
    
    // etc
    
    return query.AsEnumerable();
    

    另一种选择是在查询中添加参数检查条件

    var query = 
       from s in Context.Suppliers
       where (String.IsNullOrEmpty(nameMatch) || s.SupplierName == nameMatch) &&
             (String.IsNullOrEmpty(contactMatch) || s.ContactName == contactMatch)
             // etc
       select s;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-17
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多