How do I use anonymous type in LINQ?
Category: System.Linq, viewed: 2K time(s).
In this example we use an anonymous type as the return of our LINQ query execution. Using the anonymous type gives LINQ a powerful flexibility because we don't need to create a specific object for each type of result we want out query to return.
In the example below we query the Book data source. The Book class only have two properties the Title and the Price. But in the query we also want to calculate the tax value and the total price of the book after tax. As you can see that we also can do a calculation inside the LINQ query.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Kodecsharp.Example.Linq
{
class LinqAnonymousType
{
[STAThread]
public static void Main(string[] args)
{
List<Book> dataSource = new List<Book>() {
new Book("Windows Forms in Action", 50.00f),
new Book("Programming C#", 35.99f),
new Book(".NET Framework Essentials", 49.99f),
new Book("Beginning Visual Basic .NET", 25.00f),
new Book("Professional Crystal Reports", 45.00f)
};
var query = from book in dataSource
where book.Price > 30
select new
{
book.Title,
book.Price,
Tax = book.Price * 0.1,
TotalPrice = book.Price + book.Price * 0.1
};
foreach (var result in query)
{
Console.WriteLine("Title : " + result.Title);
Console.WriteLine("Net Price : " + result.Price.ToString("#0.00"));
Console.WriteLine("Tax : " + result.Tax.ToString("#0.00"));
Console.WriteLine("Total Price: " + result.TotalPrice.ToString("#0.00"));
Console.WriteLine("===================================================");
}
Console.ReadLine();
}
}
class Book
{
private string title;
private float price;
public Book(string title, float price)
{
this.title = title;
this.price = price;
}
public string Title
{
get { return this.title; }
set { this.title = value; }
}
public float Price
{
get { return this.price; }
set { this.price = value; }
}
}
}
Here is the output of our program:
Title : Windows Forms in Action
Net Price : 50.00
Tax : 5.00
Total Price: 55.00
===================================================
Title : Programming C#
Net Price : 35.99
Tax : 3.60
Total Price: 39.59
===================================================
Title : .NET Framework Essentials
Net Price : 49.99
Tax : 5.00
Total Price: 54.99
===================================================
Title : Professional Crystal Reports
Net Price : 45.00
Tax : 4.50
Total Price: 49.50
===================================================