Wednesday, March 18, 2009

Object Initializers with Anonymous Types



Object Initializers with Anonymous Types




In C# 3.0, we can use object initializers with anonymous types. The following example shows how it can be done:

The Customer class is an arbitrary class that we want to use in this example:


public class Customer
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}


We declare a colloecton of customers by employing "object initializers":


List customers = new List
{
new Customer { CustomerID = 99, FirstName = "Brian" , LastName = "White"},
new Customer { CustomerID = 100, FirstName = "Nicole" , LastName = "Stewart"},
new Customer { CustomerID = 101, FirstName = "Lucy" , LastName = "Brothers"}
};

Now, we create a LINQ query where the returning objects have anonymous types; an anonymous type that has two properties: ID and Name; and also we employ the object initializer concept to initialize the properties of our objects:


var selCust = from c in customers
where c.CustomerID <= 100
orderby c.LastName, c.FirstName
select new { ID = c.CustomerID, Name = c.FirstName + " " + c.LastName};


The variable selCust contains objects of an anonymous type with their properties already set (initialized). To confirm this, run the following code snippet:


foreach (var cust in selCust)
{
Console.WriteLine(cust.ID.ToString() + " " + cust.Name);
}

No comments:

Post a Comment