Tuesday 23 October 2007

LINQ - Best Practices with Anonymous Types

Anonymous types allow you to return data from multiple LINQ objects which are strongly typed, determined at runtime. However, anonymous types only have local scope. I believe that best practice with LINQ objects is to NOT cast the anonymous type to an object and consume it (because designers e.g. datagrid cannot determine the properties of the type).

Instead of casting to objects and consuming, you should really create a wrapper class which defines the standard contract that can be returned from your data access layer.

Example:



   1:  using System;

   2:  using System.Collections.Generic;

   3:  using System.Text;

   4:  using System.Linq;

   5:  using System.Configuration;

   6:  using LendLease.InvestmentManagement.AssetMaintenance.Entities;

   7:   

   8:  namespace LendLease.InvestmentManagement.AssetMaintenance.Services

   9:  {

  10:      public class CityName

  11:      {

  12:          public string DisplayValue {get; set;}

  13:      }

  14:      class AddressService : IAddressService 

  15:      {

  16:   

  17:          static AddressService()

  18:          {

  19:          }

  20:   

  21:          public IList<CityName> GetAllCities()

  22:          {

  23:              InvestmentManagementDbDataContext context =

  24:                   new InvestmentManagementDbDataContext();

  25:   

  26:              var query = (from ps in context.Addresses

  27:                          select new CityName { DisplayValue = ps.City }).Distinct();

  28:              return query.ToList();

  29:          }

  30:      }

  31:  }





For more info, see http://weblogs.asp.net/scottgu/archive/2007/05/15/new-orcas-language-feature-anonymous-types.aspx?CommentPosted=true
and http://blogs.msdn.com/miah/archive/2007/09/07/outsmarting-the-limitations-of-anonymous-types.aspx for some more comments on this.

No comments: