如何在C#中使用LINQ和Lambda来进行Join操作?

王林
发布: 2023-08-23 09:45:02
转载
1314 人浏览过

如何在C#中使用LINQ和Lambda来进行Join操作?

内连接仅返回那些在两个表中匹配或存在的记录或行。我们还可以根据条件在多个表上应用连接,如下所示。

如果我们需要根据多个条件进行连接,请使用匿名类型。

在下面的示例中,我们写了两种可以用于在Linq中进行连接的方法 这里部门和员工被连接起来

示例

class Program{
   static void Main(string[] args){
      var result =
      Employee.GetAllEmployees().Join(Department.GetAllDepartments(),
      e => e.DepartmentID,
      d => d.ID, (employee, department) => new{
         EmployeeName = employee.Name,
         DepartmentName = department.Name
      });
      foreach (var employee in result){
         Console.WriteLine(employee.EmployeeName + "\t" +
         employee.DepartmentName);
      }
      var result1 = from e in Employee.GetAllEmployees()
      join d in Department.GetAllDepartments()
      on e.DepartmentID equals d.ID
      select new{
         EmployeeName = e.Name,
         DepartmentName = d.Name
      };
      foreach (var employee in result1){
         Console.WriteLine(employee.EmployeeName + "\t" +
         employee.DepartmentName);
      }
      Console.ReadLine();
   }
}
public class Employee{
   public int ID { get; set; }
   public string Name { get; set; }
   public int DepartmentID { get; set; }
   public static List<Employee> GetAllEmployees(){
      return new List<Employee>(){
         new Employee { ID = 1, Name = "A", DepartmentID = 1 },
         new Employee { ID = 2, Name = "B", DepartmentID = 2 },
         new Employee { ID = 3, Name = "B", DepartmentID = 1 },
         new Employee { ID = 4, Name = "V", DepartmentID = 1 },
         new Employee { ID = 5, Name = "F", DepartmentID = 2 },
         new Employee { ID = 6, Name = "R", DepartmentID = 2 },
         new Employee { ID = 7, Name = "TT", DepartmentID = 1 },
         new Employee { ID = 8, Name = "YY", DepartmentID = 1 },
         new Employee { ID = 9, Name = "WW", DepartmentID = 2 },
         new Employee { ID = 10, Name = "QQ"}
      };
   }
}
public class Department{
   public int ID { get; set; }
   public string Name { get; set; }
   public static List<Department> GetAllDepartments(){
      return new List<Department>(){
         new Department { ID = 1, Name = "IT"},
         new Department { ID = 2, Name = "HR"},
         new Department { ID = 3, Name = "Contract"},
      };
   }
}
登录后复制

输出

A IT
B HR
B IT
V IT
F HR
R HR
TT IT
YY IT
WW HR
A IT
B HR
B IT
V IT
F HR
R HR
TT IT
YY IT
WW HR
登录后复制

以上是如何在C#中使用LINQ和Lambda来进行Join操作?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板