使用Linq to EF使用数组作为搜索参数进行搜索

时间:2018-11-15 10:31:51

标签: c# entity-framework linq

我已经从这里阅读并尝试了几个链接,但没有一个非常合适。

我有一个查询,当前正在使用数字或“ ||”进行搜索我需要用动态分配的列表替换的子句。它可以是数组或List <>

我当前的代码:

    var mainPull = (from c in cDb.DistributionStopInformations
                    join rh in cDb.DistributionRouteHeaders on c.Route_Code equals rh.Route_Code
                    where c.Created_By == null && c.Company_No == 1 &&
                   (c.Customer_No == 228 || c.Customer_No == 227) &&
                   (c.Branch_Id == "MEM" || c.Branch_Id == "TXK" || c.Branch_Id == "TUP" || c.Branch_Id == "LIT")
                   &&
                    c.Shipment_Type == "D" &&
                   (c.Datetime_Created > dateToSearch || c.Datetime_Updated > dateToSearch) &&
                   rh.Company_No == 1 &&
                   rh.Route_Date >= routeDateToSearch
                    orderby c.Unique_Id_No descending
                    select new
                    {
                        c.Datetime_Updated,
                        c.Datetime_Created,

我需要这样的(密码)

 string[] brancheSearchList = new string[] { "TUP", "LIT" };
            List<string> branchList = new List<string>();
            branchList.Add("TUP");
            branchList.Add("LIT")


            var mainPull = (from c in cDb.DistributionStopInformations
                            join rh in cDb.DistributionRouteHeaders on c.Route_Code equals rh.Route_Code
                            where c.Created_By == null && c.Company_No == 1 &&
                           (c.Customer_No == 228 || c.Customer_No == 227) &&
                           (c.Branch_Id IS IN branchesSearchList)

1 个答案:

答案 0 :(得分:0)

list.Contains应该生成WHERE <column> IN (<comma separated values>)

var branches = new[] { "TUP", "LIT" };
var result = 
    cDb.DistributionStopInformations
       .Join(cDb.DistributionRouteHeaders, info => info.Route_Code, h => h.Route_Code)
       .Where(info => info.Created_By == null)
       .Where(info => info.Shipment_Type == "D")
       .Where(info => branches.Contains(info.Branch_Id)) // WHERE Branch_Id IN (...)
       .ToList();