Code Elegance

DTO and LINQ

I would like to say a little thing about DTO.

With the advent of LINQ most of the things that I wrote in my old post are not necessary anymore. With the new C# 3.0 is not necessary to build a custom new class for every DTO, you can use the capability called Anonymous Type to create new types on the fly.

Take as example the (usual) case of Customer Address objects, and as the lasts post we want to show on a table the list of Customers with their FullAddress.

With LINQ is not necessary to write a new CustomerDTO class, you can use the following code to obtain the same result:

public IEnumerable GetCustomers() { IList<Customer> customers = LoadCustomerFromDB(); IEnumerable list = from c in customers select new { Name=c.Name, FullAddress=(c.Address.Street + + c.Address.City) }; return list; }

This snippet create a new Anonymous Type with two properties (Name and FullAddress) without the need to create a custom class.

2 comments