LINQ中的动态WHERE子句

LINQ中的动态WHERE子句

将动态WHERE子句组装到LINQ语句的最佳方法是什么?

我在表单上有几十个复选框,并将它们传递回:Dictionary <string,List <string >>(Dictionary <fieldName,List <values >>)到我的LINQ查询。

public IOrderedQueryable<ProductDetail> GetProductList(string productGroupName, string productTypeName, Dictionary<string,List<string>> filterDictionary){
    var q = from c in db.ProductDetail
            where c.ProductGroupName == productGroupName && c.ProductTypeName == productTypeName            // insert dynamic filter here
            orderby c.ProductTypeName
            select c;
    return q;}


茅侃侃
浏览 960回答 3
3回答

ibeautiful

我有类似的场景,我需要根据用户输入添加过滤器,并链接where子句。这是示例代码。var&nbsp;votes&nbsp;=&nbsp;db.Votes.Where(r&nbsp;=>&nbsp;r.SurveyID&nbsp;==&nbsp;surveyId);if&nbsp;(fromDate&nbsp;!=&nbsp;null){ &nbsp;&nbsp;&nbsp;&nbsp;votes&nbsp;=&nbsp;votes.Where(r&nbsp;=>&nbsp;r.VoteDate.Value&nbsp;>=&nbsp;fromDate);}if&nbsp;(toDate&nbsp;!=&nbsp;null){ &nbsp;&nbsp;&nbsp;&nbsp;votes&nbsp;=&nbsp;votes.Where(r&nbsp;=>&nbsp;r.VoteDate.Value&nbsp;<=&nbsp;toDate);}votes&nbsp;=&nbsp;votes.Take(LimitRows).OrderByDescending(r&nbsp;=>&nbsp;r.VoteDate);
打开App,查看更多内容
随时随地看视频慕课网APP