首页 > 解决方案 > linq中的sql where子句规则

问题描述

我正在尝试将我的 SQL 规则放在 Linq 中,因为我的规则是从查询生成器生成的,我需要根据规则过滤我的数据,这是我的简单示例

class Program
{
    static void Main(string[] args)
    {
        PromotionVm lObjPromVm = new PromotionVm();
        for (int i = 1; i <= 5; i++)
        {
            PromotionList lObjPromList = new PromotionList();
            lObjPromList.active_indicator = 1;
            lObjPromList.principle_code = "a" + i;
            lObjPromList.promotion_code = "b" + i;
            lObjPromList.promotion_plan_number = 20 + i;
            lObjPromList.promotion_type_code = 30 + i;
            lObjPromList.start_date = DateTime.Now.AddDays(i);
            lObjPromVm.promotion_list.Add(lObjPromList);
        }

        //var sqlRule= "promotion_type_code = 'expensive' AND Category IN('Food', 'Transportation', 'Shopping') AND(PaymentMode = 'Cash' OR PaymentMode = 'Debit Card' OR(Amount = 35))";
        var sqlRule = "promotion_type_code = '33'";
        //  lObjPromVm.promotion_list.ToDataTable()
        var lOutlut = lObjPromVm.promotion_list.Where(sqlRule);
    }
}

class PromotionVm
{
    public List<PromotionList> promotion_list { get; set; }
    public PromotionVm()
    {
        promotion_list = new List<PromotionList>();
    }
}
    
public class PromotionList
{
    public string principle_code { get; set; }
    public string promotion_code { get; set; }
    public int promotion_plan_number { get; set; }
    public int promotion_type_code { get; set; }
    public DateTime start_date { get; set; }
    public int active_indicator { get; set; }
}

我正在尝试使用System.Linq.Dynamic.Core;但不工作。

谁能建议我如何通过 SQL 规则过滤我的数据?在这里问了同样的问题如何在 linq where 子句中使用字符串? 但是响应给出的内容,它不起作用。

标签: c#linq

解决方案


我能够解决问题,我只需要转换为AsQueryable().

var sqlRule = "promotion_type_code in (31,33) or (promotion_code=\"b2\")";
var lOutlut = lObjPromVm.promotion_list.AsQueryable().Where(sqlRule);

推荐阅读