Data Grouping in LINQ

Data Grouping is another feature of LINQ syntax, which can group data based on data collection’s filter element or key character.

The keyword used in Data Grouping is group and on.

Data Source

Manufacturer Sample

Car Sample

Class Definition

Car Class

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; }
     }

Manufacturer Class

public class Manufacturer
     {
         public string Name { get; set; }
         public string Headquarters { get; set; }
         public int Year { get; set; }
     }

Data Grouping Implementation

static void Main(string[] args)
{
    var cars = ProcessCars("fuel.csv");
    var manufacturers = ProcessManufacturers("manufacturers.csv");
    var query = from car in cars             
                group car by car.Manufacturer;         

    foreach(var result in query) 
       {  
         Console.WriteLine($"{result.Key} has {result.Count()} cars");         
       }         
       Console.ReadLine();     
}

As we can see, we group the data via the car’s manufacturer details, such as Toyota, BMW, etc.

We use keyword group-by to project our result. The result.Key represents the filter element.

Output

As we are expecting, the output console prints out number of model for each car manufacturer, respectively.


Keyword Into

Still with the project, we can use keyword into to make a new variable, which points to the new project data element.

static void Main(string[] args)
{
    var cars = ProcessCars("fuel.csv");
    var manufacturers = ProcessManufacturers("manufacturers.csv");
    var query =             
             from car in cars             
             group car by car.Manufacturer.ToUpper() 
             into manufacturer //we lost car as a variable here             
             orderby manufacturer.Key             
             select manufacturer;                 
     foreach(var group in query)         
       { 
          Console.WriteLine(group.Key);             
          foreach(var car in group.OrderByDescending(c =>c.Combined).Take(2))             
              { 
                Console.WriteLine($"\t{ car.Name} : {car.Combined}");             
               }         
         }         
Console.ReadLine();     
}

As we can see, after the keyword into, we have lost the car as a variable. On Line 14, we need to declare a variable named car when we retrieved each individual element from the group.

Output


Leave a Reply

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