Anonymous Type in LINQ

Anonymous type in LINQ query is useful when parts of the data are needed, especially the output type is relatively large.

Convert Data into Object

The first step of LINQ process is to turn data into objects.

static void Main(string[] args) 
{
    var cars = ProcessFile("fuel.csv");
}

Function ProcessFile() turns the data source into object.

Helper function

private static List<Car> ProcessFile(string path)
{
    var query = File.ReadAllLines(path)
                    .Skip(1)
                    .Where(line => line.Length > 1)
                    .ToCar();
}

Data Source

Data source in this post is a a list of car’s detail and it is saved in a .csv file.


Data Model – Car

public class Car 
{
    public int Year { get; set; }
    public string Manufacturer { get; set; }
    public string Name { get; set; }
    public double Displacement { get; set; }
    public int Cylinders { get; set; }
    public int City { get; set; }
    public int Highway { get; set; }
    public int Combined { get; set;}
}

Car Extension Method

The Car extension method is called when LINQ breaks the original data into individual line.

public static class CarExtensions
{
   public static IEnumerable<Car> ToCar(this IEnumerable<string> source)
    {
        foreach(var line in source)
           {
               var columns = line.Split(',');
               yield return new Car 
               {
                    Year = int.Parse(columns[0]),
                    Manufacturer = columns[1],
                    Name = columns[2],
                    Displacement = double.Parse(columns[3]),
                    Cylinders = int.Parse(columns[4]),
                    City = int.Parse(columns[5]),
                    Highway = int.Parse(columns[6]),
                    Combined = int.Parse(columns[7])
               };  
           }
    }
}

Object Process

static void Main(string[] args) 
{
    var cars = ProcessFile("fuel.csv");

    var query = 
        from car in cars
        where car.Manufacturer == "BMW" && car.Year == 2016
        orderby car.Combined descending, car.Name ascending
        select new { //Annoymous Class
               car.Manufacturer,
               car.Name,
               car.Combined
        };

    foreach(var car in query.Take(10))
    {
      Console.WriteLine($"{car.Manufacturer} : {car.Name} : {car.Combined}");
    }
}

As we can see from the above code, the query did not select a Car object; instead, query creates an anonymous type, which has three properties, Manufacturer, Name and Combined.


Leave a Reply

Your email address will not be published. Required fields are marked *