Joining Multiple Data-Sources using 'Concat' Key in LINQ - Part 7

This is seventh part of the ‘LINQ’ series posts that I have started from here. In the last post we explored how to filter, order, group and join in LINQ. Now, in this post we will take a look at concate key used LINQ query to do joins.


Assume if we have following data source information:

Student.cs

    class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public List<int> Marks { get; set; }
    }

Teacher.cs

    class Teacher
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }

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 name and Teacher’s who is from ‘Bokaro’ by concat. So, we can use 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 output is:

Abhimanyu K Vatsa
Geeta K
Ranjeet Kumar

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

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

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System