Joining Multiple Data-Sources Using "Concat" Key in LINQ: Part 7

This is seventh part of the "LINQ" series of articles that I have started from here. In the last article we explored how to filter, order, group and join in LINQ. Now, in this article we will take a look at doing joins using Concat key in a LINQ query.
 

Assume we have the following data source information:


Student.cs

 

    class Student

    {

        public int ID { getset; }

        public string Name { getset; }

        public string Address { getset; }

        public List<int> Marks { getset; }

    }


 

Teacher.cs
 

    class Teacher

    {

        public int ID { getset; }

        public string Name { getset; }

        public string Address { getset; }

    }


 

Program.cs
 

//DataSource1

List<Student> students = new List<Student>()

{

    new Student { ID=1, Name="Abhimanyu K Vatsa", Address="Bokaro", Marks= new List<int> {97, 92, 81, 90}},

    new Student { ID=2, Name="Deepak Kumar", Address="Dhanbad", Marks= new List<int> {70, 56, 87, 69}},

    new Student { ID=3, Name="Mohit Kumar", Address="Dhanbad", Marks= new List<int> {78, 76, 81, 56}},

    new Student { ID=4, Name="Geeta K", Address="Bokaro", Marks= new List<int> {95, 81, 54, 67}}

};
 

//DataSource2

List<Teacher> teachers = new List<Teacher>()

{               

    new Teacher {ID=1, Name="Ranjeet Kumar", Address = "Bokaro"},

    new Teacher {ID=2, Name="Gopal Chandra", Address = "Dhanbad"}

};


And I want to select those Student's names and Teachers from "Bokaro" by Concat. So, we can use a LINQ query to create an output sequence that contains elements from more than one input sequence. Here it is:
 

//Query using Concat

var query = (from student in students

                        where student.Address == "Bokaro"

                        select student.Name)

                .Concat(from teacher in teachers

                        where teacher.Address == "Bokaro"

                        select teacher.Name);


And the output is:
 

Abhimanyu K Vatsa

Geeta K

Ranjeet Kumar


Remember, this also can be done using join, that we already saw in one of the previous articles.
 

I hope you will find it useful. Thanks for reading.


Similar Articles