GroupBy Example with LINQ

Posted: April 7, 2012 in .NET
Tags: , , ,

Here is an example of aggregation using LINQ to a collection –

 

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

namespace GroupByExampleLinq
{
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string AccountNumber { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Example();
            Console.ReadKey();
        }

        static void Example()
        {
            // Creating new List of Person
            List personCollection = new List()
            {
                //Adding a new Person
                new Person(){
                    AccountNumber = "123123 634566",
                    Email = "qwerty@qwerty.com",
                    FirstName = "John",
                    LastName = "Doe"
                },
                //Adding a new Person
                new Person(){
                    AccountNumber = "123123 678879",
                    Email = "qwerty@qwerty.com",
                    FirstName = "John",
                    LastName = "Doe"
                },
                //Adding a new Person
                new Person(){
                    AccountNumber = "123123 122134",
                    Email = "qwerty@qwerty.com",
                    FirstName = "John",
                    LastName = "Doe"
                },
                //Adding a new Person
                new Person(){
                    AccountNumber = "123123 890980",
                    Email = "asdf@asdf.com",
                    FirstName = "Jane",
                    LastName = "Doe"
                }
            };

            // Using LINQ to query the collection and group them by the email address
            var personQuery = from p in personCollection
                              group p by p.Email into g
                              select new { Email = g.Key, Accounts = g };

            // Output the email address and the count of records for each group
            foreach (var item in personQuery)
            {
                Console.WriteLine("{0} has {1} accounts.", item.Email, item.Accounts.Count());
            }
        }
    }
}

Comments
  1. Bahadir says:

    Thx :=)

Leave a comment