LINQ语句中如何将where语句发送到动态执行的方法?在下面的示例中,GetFilteredCustomers()工作正常,因此我可以为客户发送我想要的姓氏的各种字母。但是我如何构建GetFilteredCustomersDynamic(),这将使我能够发送一个可以动态包含在LINQ语句中的完整where子句?使用System.Collections.Generic;使用System.Linq;使用系统文本;命名空间TestDynamicLinq2343{公共类程序{staticvoidMain(string[]args){列出客户=Customer.GetCustomers();//半动态foreach(varcustomerinCustomer.GetFilteredCustomers(customers,"o")){Console.WriteLine(customer.LastName);}//全动态(可以发送where子句)}控制台.ReadLine();}}publicclassCustomer{publicstringFirstName{get;放;}publicstringLastName{get;放;}publicstringStreet{get;放;}公共字符串位置{得到;放;}publicstringZipCode{get;放;}publicstaticListGetCustomers(){列出客户=newList();customers.Add(新客户{FirstName="Jim",LastName="琼斯"});customers.Add(newCustomer{FirstName="Joe",LastName="Adams"});customers.Add(newCustomer{FirstName="Jake",LastName="Johnson"});回头客;}publicstaticListGetFilteredCustomers(Listcustomers,stringletter){return(fromcincustomerswherec.LastName.Contains(letter)selectc).ToList();}publicstaticListGetFilteredCustomersDynamic(Listcustomers,FuncwhereClause){return(fromcincustomerswhere...whereClause...selectc).ToList();}}}回复:感谢elder_george和arjuns,我让这个例子像这样工作(尽管没有表达式):usingSystem;使用System.Collections.Generic;使用System.Linq;命名空间TestDynamicLinq2343{公共类程序{staticvoidMain(string[]args){列出客户=Customer.GetCustomers();FuncwhereClause=c=>c.LastName.Contains("a")&&c.FirstName.Contains("J");foreach(varcustomerinCustomer.GetFilteredCustomers(customers,whereClause)){Console.WriteLine(customer.}控制台.ReadLine();}}publicclassCustomer{publicstringFirstName{get;放;}publicstringLastName{get;放;}publicstringStreet{get;放;}公共字符串位置{得到;放;}publicstringZipCode{get;放;}publicstaticListGetCustomers(){列出客户=newList();customers.Add(newCustomer{FirstName="Jim",LastName="Jones"});customers.Add(newCustomer{FirstName="Joe",LastName="Adams"});customers.Add(newCustomer{FirstName="Jake",LastName="Johnson"});customers.Add(newCustomer{FirstName="Angie",LastName="Reckar"});customers.Add(newCustomer{FirstName="Jean-Luc",LastName="Beaudoir"});回头客;}publicstaticListGetFilteredCustomers(Listcustomers,FuncwhereClause){returncustomers.Where(whereClause).ToList();您需要将过滤器表达为Expression>,而不是Func这样,您可以使用Queryable.Where方法将此过滤器添加到LINQ表达式树中。编辑:我错了,因为此代码使用LINQtoObject,其中委托是适当的过滤条件。我的错。例如(更正为使用普通委托):publicstaticListGetFilteredCustomersDynamic(Listcustomers,FuncwhereClause){}publicstaticListGetFilteredCustomers(Listcustomers,stringletter){returnGetFilteredCustomersDynamic(=>c.LastName.Contains(letter));}试试这段代码,publicstaticListGetFilteredCustomersDynamic(Listcustomers,Expression>whereClause){returncustomers.Where(whereClause.Compile()).ToList();}@elder_george,有一个错字,应该为它的委托编译表达式,否则编译失败。返回客户.Where(whereClause).ToList();应该理解为以上是C#学习教程:如何将where语句发送到LINQ语句中动态执行的方法?如果分享的内容对你有用,需要了解更多C#学习教程,希望你多多关注——回馈客户.Where(whereClause.Compile()).ToList();本文收集自网络,不代表立场,如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处:
