C# LINQ Grouping Operator

Updated on     Kisan Patel

The group operator transforms sequence into a sequence of groups.

The group operator can be used to project a result grouped by a key. It can be used as an alternative to the from clause and allows you to use single-value keys as well as multiple-value keys.

The group operator implements IGrouping<TKey, T> interface.

The group operator will end a query, use into to continue the query.

For Example,

var query = from c in customers
                group customers by c.City
                   into groupbyCities
                      orderby groupbyCities.Key ascending
                      select groupbyCities;

Let’s take example to understand how group operator works.

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

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            List customers = new List{
                                            new Customer{ Id = 1, Name = "Kisan", City="Ladol" },
                                            new Customer{ Id = 2, Name = "Kite", City = "Ladol" },
                                            new Customer{ Id = 3, Name = "Ketul", City = "Vijapur" },
                                            new Customer{ Id = 4, Name = "Kisan", City = "Vijapur" },
            };

            var query = from c in customers
                        group c by c.City;

            foreach (var group in query)
            {
                Console.WriteLine("Group City : " + group.Key);
                foreach (var name in group)
                {
                    Console.WriteLine(name.Id + " - " + name.Name);
                }
            }
        }
    }

    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
    }

}

the output of the above C# program…

linq-group-operator-demo


C# LINQ

Leave a Reply