How to project an anonymous type (LINQ to XML)

In some cases, you might want to project a query to a new type, but the query would be your only use for the new type. Rather than create the type, you can project to an anonymous type. Anonymous types provide a convenient way to encapsulate a set of read-only properties in an object without having to explicitly define a type first. If you write a query that creates an object of an anonymous type in the select clause, the query returns an IEnumerable of the type.

The following example shows creation of an object of an anonymous type that's initialized with two properties, Amount and Message.

var v = new { Amount = 108, Message = "Hello" };
Dim v = New With { .Amount = 108, .Message = "Hello" };

The type of each property is inferred by the compiler. The type name is generated by the compiler and isn't available at the source code level.

For more information about anonymous types, see:

Example: Project an anonymous type by creating objects in the select clause

In this example, the select clause projects an anonymous type. The example then uses var to create the IEnumerable object. Within the foreach loop, the iteration variable becomes an instance of the anonymous type created in the query expression.

This example uses XML document Sample XML file: Customers and orders.

XElement custOrd = XElement.Load("CustomersOrders.xml");
var custList =
    from el in custOrd.Element("Customers").Elements("Customer")
    select new {
        CustomerID = (string)el.Attribute("CustomerID"),
        CompanyName = (string)el.Element("CompanyName"),
        ContactName = (string)el.Element("ContactName")
    };
foreach (var cust in custList)
    Console.WriteLine("{0}:{1}:{2}", cust.CustomerID, cust.CompanyName, cust.ContactName);
Dim custOrd As XElement = XElement.Load("CustomersOrders.xml")
Dim custList = _
    From el In custOrd.<Customers>.<Customer> _
    Select New With { _
        .CustomerID = el.@<CustomerID>, _
        .CompanyName = el.<CompanyName>.Value, _
        .ContactName = el.<ContactName>.Value _
    }
For Each cust In custList
    Console.WriteLine("{0}:{1}:{2}", cust.CustomerID, cust.CompanyName, cust.ContactName)
Next

This example produces the following output:

GREAL:Great Lakes Food Market:Howard Snyder
HUNGC:Hungry Coyote Import Store:Yoshi Latimer
LAZYK:Lazy K Kountry Store:John Steel
LETSS:Let's Stop N Shop:Jaime Yorres

See also