The join operator

The join operators in LINQ help us join two collections that could be linked to each other by a common attribute. Refer to the following code example, which will provide a better explanation of this. Consider that we have two class objects, one representing ClassDetail and another representing Students that are studying in the class:

public class Student
{
public int rollNum { get; set; }
public string Name { get; set; }
public string classID { get; set; }
}
public class ClassDetail
{
public string classID { get; set; }
public string className { get; set; }
}

Please note that in the ClassDetail class, we have details specific to the class in itself such as ClassID and ClassName. In the Student class, we have details specific to the student such as rollNum, Name, and ClassID. In the Student class, ClassID attribute refers to the class in which the student is currently studying. We will use this attribute to link the collections of ClassDetail and Student.

The following code indicates how we make a join between the two collection items of Student and Class:

 List<ClassDetail> classNames = new List<ClassDetail>();
classNames.Add(new ClassDetail { classID = "1", className = "First Standard" });
classNames.Add(new ClassDetail { classID = "2", className = "Second Standard" });
classNames.Add(new ClassDetail { classID = "3", className = "Third Standard" });
List<Student> students = new List<Student>();
students.Add(new Student { rollNum = 1, classID = "1", Name = "Sia Bhalla" });
students.Add(new Student { rollNum = 2, classID = "2", Name = "James Donohoe" });
students.Add(new Student { rollNum = 3, classID = "1", Name = "Myra Thareja" });
var list = (from s in students
join d in classNames on s.classID equals d.classID
select new
{
StudentName = s.Name,
ClassName = d.className
});
foreach (var e in list)
{
Console.WriteLine("Student Name = {0} , Class Name = {1}", e.StudentName, e.ClassName);
}

In the preceding code, we have created two collections lists, one each of Student and ClassDetail. Then, using a join operator, we are combining the two lists based on a common attribute, ClassID. In the resultant items, we are then saving the name of the student and the name of the class. If the code is executed, we will get the following output:

In the next section, we will look at the orderby operator.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.40.63