Sunday, February 14, 2010

LINQ: Anonymous Class - select new

http://nayyeri.net/use-anonymous-types-to-select-data-in-linq

When using LINQ, normally you select data by using regular types.  But thank to new language features in .NET 3.5, you're able to select entities with Anonymous Types, too.  Follow this post to see how!

Sample Application

Let me write a simple sample console application to use in this post.  After creating this console application for .NET 3.5, I create a database with two tables named Person and Address.  As names suggest, they keep data for persons and their addresses and there is a relationship between a field in Address and a field in Person.
Now I add a new LINQ to SQL file to my project and drop my tables into it.
Tables
Now that I have all generated classes for my purpose, I can implement my code in the console application.

Select Entities with Anonymous Types

First I write a simple code to select the name of persons.
static void Main(string[] args)
{
    Console.Title = "Use Anonymous Types to Select Entities in LINQ";

    DataClasses1DataContext dataContext = new DataClasses1DataContext();

    var myQuery = from p in dataContext.Persons
                  select p.Name;

    foreach (var person in myQuery)
    {
        Console.WriteLine(person);
    }

    Console.ReadLine();
}
Output
Don't laugh to sample data, please!!
This was a sample of selecting all persons with a normal string type for their Name field.  But alternatively, you can select them with anonymous types to have a combination of them.
static void Main(string[] args)
{
    Console.Title = "Use Anonymous Types to Select Entities in LINQ";

    DataClasses1DataContext dataContext = new DataClasses1DataContext();

    var myQuery = from p in dataContext.Persons
                  select new { p.Name, p.Age };

    foreach (var person in myQuery)
    {
        Console.WriteLine(person);
    }

    Console.ReadLine();
}
Output
Using anonymous types, I can also get the benefit of assigning new names to data fields as is shown below.
static void Main(string[] args)
{
    Console.Title = "Use Anonymous Types to Select Entities in LINQ";

    DataClasses1DataContext dataContext = new DataClasses1DataContext();

    var myQuery = from p in dataContext.Persons
                  select new
                        {
                            PersonName = p.Name,
                            PersonAge = p.Age,
                            PersonAddress = p.Address.Line1 + "\n" +
                            p.Address.Line2 + "\n" +
                            p.Address.Zip
                        };

    foreach (var person in myQuery)
    {
        Console.WriteLine(person);
    }

    Console.ReadLine();
}
Output

No comments: