LINQ | Grouping Operator | GroupBy

In LINQ, grouping is done by selecting items containing common features of the row or collection and presenting them in a group. In simple words, GroupBy groups the items according to the key. This group is kept in a special collection that occurs from Key and Element. Key is common feature where you want to group your items or collect your items according to. And key can be any data type as int, float, string etc. Furthmore key can be concatenation of some attributes, or a result of operation with some attributes. Element is the collection where you collect according to your key.

Let’s assume we have a Car class and this class has Name, Model and Price properties. We have a list of cars and just want to group them according to their Name property.

This is our car class

public class Car {
        public Car(string name, string model, int price) {
            Name = name;
            Model = model;
            Price = price;
        }
        public string Name { get; set; }
        public string Model { get; set; }
        public int Price { get; set; }
    }

 

And we have list of cars as shown below,

List<Car> cars = new List<Car>();
cars.Add(new Car("Ford", "Fiesta", 250));
cars.Add(new Car("Ford", "Mustang", 400));
cars.Add(new Car("Renault", "Golf", 120));
cars.Add(new Car("Renault", "Megan", 250));
cars.Add(new Car("Renault", "Clio", 400));
cars.Add(new Car("Audi", "Sedan", 250));

 

Let’s consider this list as a table to make everything crystal clear,

Name Model Price
Ford Fiesta 250
Ford Mustang 400
Renault Golf 120
Renault Megan 250
Renault Clio 400
Audi Sedan 250

 

When we group list by name (grouping key) with the following code,

var carsGroupedByName = cars.GroupBy(x => x.Name).ToList();

 

Our carsGroupedByName collection will look like this,

Key Element
Name Model Price
Ford Ford Fiesta 250
Ford Mustang 400
Renault Renault Golf 120
Renault Megan 250
Renault Clio 400
Audi Audi Sedan 250

 

Now i can sum the price of grouped items. Let’s get everything together.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ZeroToCSharp {
    class Program {
        static void Main(string[] args) {
            List<Car> cars = new List<Car>();
            cars.Add(new Car("Ford", "Fiesta", 250));
            cars.Add(new Car("Ford", "Mustang", 400));
            cars.Add(new Car("Renault", "Golf", 120));
            cars.Add(new Car("Renault", "Megan", 250));
            cars.Add(new Car("Renault", "Clio", 400));
            cars.Add(new Car("Audi", "Sedan", 250));

            var carsGroupedByName = cars.GroupBy(x => x.Name).Select(x => new Car(x.Key, string.Join(",", x.Select(y => y.Model)), x.Sum(y => y.Price))).ToList();

            //To print output
            carsGroupedByName.ForEach(x => Console.WriteLine(string.Concat("Name:", x.Name, "  Models:", x.Model, "  Total Price:", x.Price)));
            Console.ReadKey();
        }
    }

    public class Car {
        public Car(string name, string model, int price) {
            Name = name;
            Model = model;
            Price = price;
        }
        public string Name { get; set; }
        public string Model { get; set; }
        public int Price { get; set; }
    }
}

Output:

Name:Ford Models:Fiesta,Mustang Total Price:650
Name:Renault Models:Golf,Megan,Clio Total Price:770
Name:Audi Models:Sedan Total Price:250

 

Now our carsGroupedByName collection will look like this,

Name Model Price
Ford Fiesta,Mustang 650
Renault Golf,Megan,Clio 770
Audi Sedan 250

 

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x