减少linq查询以进行过滤

Ang*_*gel 3 c# sql linq wpf entity-framework

我有其结合性质的视图模型3个文本框的视图SupplierName,Contact,Address结合并一个键SearchCommand场所在我的视图模型.

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

用户可以输入任何上述文本框,这些文本框会导致我编写9个不同的查询.例如,如果用户仅在SupplierName文本框上输入数据,那么我需要使用SupplierNameas参数运行一个查询.如果用户输入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();
    }
Run Code Online (Sandbox Code Playgroud)

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

Ser*_*kiy 9

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

另一个选择是添加参数检查条件以进行查询

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