Grouping Objects by using GroupBy using LINQ in C#

Ever need to group by a property and want to use LINQ to do so? Happened to me recently and decided to explore the really simple way to group objects using LINQ using GroupBy.

I started off by creating a simple class for a person and created a list

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

namespace ConsoleSandbox
{
    public class Person
    {
        public int PersonId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime Birthday { get; set; }
    }

    public class GroupByExample
    {        
        public void GroupByDate()
        {
            var people = new List<Person>
            {
                new Person { PersonId = 1, FirstName = "John", LastName = "Doe", Birthday = new DateTime(1986, 12, 27) },
                new Person { PersonId = 2, FirstName = "Jane", LastName = "Smith", Birthday = new DateTime(1990, 6, 26) },
                new Person { PersonId = 3, FirstName = "Jamaal", LastName = "Charles", Birthday = new DateTime(1986, 12, 27)},
                new Person { PersonId = 4, FirstName = "Iman", LastName = "Shumpert", Birthday = new DateTime(1990, 6, 26)}
            };            

            // Our code will go here
        }
    }    
}

Next add the following line

var groupedList = people.GroupBy(p => p.Birthday.Date);

This will group your list, people by the property Birthday. This command will result as IGrouping<TKey, TElement>. If this is your first time using this interface, imagine a Dictionary<key, value> where multiple values can be stored for each key. To iterate over the groupings, a couple of simple foreachs will work. In real scenarios, I would suggest maybe giving the resultSelector a try.

foreach (var group in groupedList)
{
    Debug.WriteLine(group.Key);
    foreach (var person in group)
    {
        Debug.WriteLine(string.Format("{0} {1}", person.FirstName, person.LastName));
    }
}            

 

Jacob Saylor

Software developer in Kentucky

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: