Zip operator in C# is used for merging or combining two sequences into one sequence.If you have two lists of elements and you want to create a third list by combining elements in the two lists then you can use Zip LINQ operator.It is included as a query operator in C# 4.0 onward.
Suppose if you have two classes defined for Employees working in your organisation and the departments to which they are assigned:
class Employee { public string Name { get; set; } public int Id { get; set; } public decimal Salary { get; set; } public int Grade { get; set; } } class EmployeeDepartment { public int Id { get; set; } public string Department { get; set; } }
In this case you will have two separate collections defined for employees and their departments:
list of employees:
List<Employee> emps = new List<Employee>(); emps.Add(new Employee { Name = "Employee1", Salary = 1000, Grade = 1 }); emps.Add(new Employee { Name = "Employee2", Salary = 1000, Grade = 2 });
list of departments:
List<EmployeeDepartment> empdepts = new List<EmployeeDepartment>(); empdepts.Add(new EmployeeDepartment {Id=1,Department="HR" }); empdepts.Add(new EmployeeDepartment { Id = 2, Department = "Finance" });
Now problem is employees are assigned to their departments based on employee Id.So if you want to see the names of the employees in the different departments then you can use:
So after sorting the list of EmployeeDepartment and Employees by their Ids you can merge the two collections:
var empDepartmens= emps.Zip(empdepts, (e, s) => e.Name+" "+s.Department );
Leave a Reply