我如何在linq或lambda中使用join和where子句编写sql查询

时间:2018-07-11 09:33:03

标签: c# linq

我在class UserLists { public static List<int> UserFiveList() { List<int> userList = new List<int>(); int userPick1 = 0; int userPick2 = 0; int userPick3 = 0; int userPick4 = 0; int userPick5 = 0; // method that fills the list void FillUserFiveList(int pick, int count) { do { Console.Write("Enter first number between 1-45 : "); pick = int.Parse(Console.ReadLine()); if (userList.Contains(pick)) Console.WriteLine("You have to enter a unique number"); else if (pick >= 1 && pick <= 45) { Console.WriteLine("Adding your first number in the list..."); userList.Add(pick); } else Console.WriteLine("You have to enter a number between 1-45"); } while (userList.Count < count); } //end of method FillUserFiveList(userPick1, 1); FillUserFiveList(userPick2, 2); FillUserFiveList(userPick3, 3); FillUserFiveList(userPick4, 4); FillUserFiveList(userPick5, 5); return userList; } public static List<int> UserOneList() { List<int> userOneList = new List<int>(); do { Console.Write("Enter your number between 1-20 : "); int userPick1 = int.Parse(Console.ReadLine()); if (userPick1 >= 1 && userPick1 <= 20) { Console.WriteLine("Adding your only number in the list..."); userOneList.Add(userPick1); } else Console.WriteLine("You have to enter a number between 1-20"); } while (userOneList.Count < 1); return userOneList; } } 中编写了以下查询,现在我想使用C#MsSQL

编写此查询
linq

2 个答案:

答案 0 :(得分:3)

一个相当简单的join就可以了。

from jd in Job_Details 
join cust in MstCustomer
on jd.Cust_ID equals cust.Cust_ID
where cust.SAP == 'Yes'
select jd

答案 1 :(得分:1)

您使用lambda表达式要求

您只希望Cust.SAP的客户等于“是”,但不希望SAP最终结果。因此,仅在最终结果中仅与您真正想要的客户一起加入会更有效率。因此,请在Where之前做Join

IQueryable<JobDetail> jobDetails = ...
IQueryable<Customer> mstCustomers = ...

// Step 1: filter only the Yes customers:
var yesCustomers = mstCustomers.Where(customer => customer.SAP == "Yes");

// Step 2: Perform the join and select the properties you want:
var result = jobDetails.Join(yesCustomers, // Join jobDetails and yesCustomers
   jobDetail => jobDetail.Cust_Id,         // from every jobDetail take the Cust_Id
   customer = customer.Cust_Id,            // from every customer take the Cust_Id
   (jobDetail, customer) => new            // when they match use the matching items
   {                                       // to create a new object
       // select only the properties
       // from jobDetail and customer
       // you really plan to use
   })

TODO:如果需要,使它成为一条大的LINQ语句。请注意,这不会对性能产生太大影响,因为这些语句不会执行查询。它们仅更改查询的Expression。只有不返回IQueryable的项目才执行查询:ToList / FirstOrDefault / Any / Max / ...