Group join is very useful when you want to join two collection list using LINQ query, GroupJoin operator is almost same as LINQ Join operator.
GroupJoin does almost same task, the only difference is that GroupJoin returns a result set in a group form based on some specified key.
We have learned LINQ Join Operator in earlier tutorial.
Let's learn how to write GroupJoin in LINQ by example.
First we create two lists with a common Id.
Here we have created a student list and stream list, and there is a common property, which will establish the relation between the collections.
IList<Student> studentList = new List<Student>(); studentList.Add(new Student() { StudentId = 1, FullName = "Mark", StreamId = 1 }); studentList.Add(new Student() { StudentId = 2, FullName = "Archana", StreamId = 2 }); studentList.Add(new Student() { StudentId = 3, FullName = "Denis", StreamId = 1 }); studentList.Add(new Student() { StudentId = 4, FullName = "Arjun", StreamId = 2 }); studentList.Add(new Student() { StudentId = 5, FullName = "Anirban", StreamId = 1 }); studentList.Add(new Student() { StudentId = 6, FullName = "Paresh", StreamId = 2 }); IList<Stream> streamList = new List<Stream>(); streamList.Add(new Stream() { StreamId = 1, StreamName = "Microsoft" }); streamList.Add(new Stream() { StreamId = 2, StreamName = "Oracle" });
Student.StreamId=Stream.StreamId
Now let's look at the GroupJoin syntax in LINQ
var grpJoin = streamList.GroupJoin(studentList, //first list str => str.StreamId, //key for second list s => s.StreamId, //key for first list (_str, stuGroup) => new // result for each group { StudentList = stuGroup, TechStreamName = _str.StreamName }); //Print the list for each Stream foreach (var item in grpJoin) { Console.WriteLine(item.TechStreamName); foreach (var stud in item.StudentList) Console.WriteLine(stud.FullName); }
We can write the same above join using query syntax
var grpJoinQuery = from str in streamList join s in studentList on str.StreamId equals s.StreamId into studentGroup select new { StudentList = studentGroup, TechStreamName = str.StreamName }; foreach (var item in grpJoinQuery) { Console.WriteLine(item.TechStreamName); foreach (var stud in item.StudentList) Console.WriteLine(stud.FullName); }
In both GroupJoin result would be the same as given below
Microsoft ============ Mark Denis Anirban Oracle ============= Archana Arjun Paresh
You may be interested in following posts: