LINQ – Return Named Type instead of Anonymous Type when Joining multiple Collections


Recently we came across a situation where we wanted to return a named type instead of anonymous type as a result of joining of two collections using LINQ. We all know that if we write a LINQ query on a single object collection we can return a named type of that collection without any problem. However when we start using joins with additional collections or start returning the partial set of properties what we really get is a anonymous object.

I have modified the actual code to explain the concept. The sample may not make any business case sense but the idea is to understand the mechanism.

In this example I am creating below mentioned classes.

image

Class EmployeeCode and Employee will be used to create object collections and will be joined using the property Code. And then we will be writing a LINQ query to return the collection of type EmployeeNew class.

Populate the EmployeeCode and Employee collections with sample data.

image

Below is the actual LINQ query. We are also looping through the resultant collection and using the read-only property Name of the EmployeeNew class to verify that the correct object is returned.

image

Console application output.

image

Many of you might already be knowing this, but just incase I thought will be something good to share. Hope you will find it useful.

Advertisements