CSharp - GroupBy operator with part of the input element being processed with the elementSelector.

Introduction

In the call to the GroupBy operator, elementSelector, the second argument, is returning the dateAwarded member.

Because we are returning a DateTime, our IGrouping is now for a type of DateTime, instead of StudentOptionEntry.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/* www.j a va2s .  co  m*/
{
    static void Main(string[] args)
    {
        StudentOptionEntry[] empOptions = StudentOptionEntry.GetStudentOptionEntries();
        IEnumerable<IGrouping<int, DateTime>> opts = empOptions
          .GroupBy(o => o.id, e => e.dateAwarded);

        //  First enumerate through the sequence of IGroupings.
        foreach (IGrouping<int, DateTime> keyGroup in opts)
        {
            Console.WriteLine("Option records for Student: " + keyGroup.Key);

            //  Now enumerate through the grouping's sequence of DateTime elements.
            foreach (DateTime date in keyGroup)
                Console.WriteLine(date.ToShortDateString());
        }
    }
}
class StudentOptionEntry
{
    public int id;
    public long optionsCount;
    public DateTime dateAwarded;

    public static StudentOptionEntry[] GetStudentOptionEntries()
    {
        StudentOptionEntry[] empOptions = new StudentOptionEntry[] {
      new StudentOptionEntry {
        id = 1,
        optionsCount = 2,
        dateAwarded = DateTime.Parse("1990/12/31") },
      new StudentOptionEntry {
        id = 2,
        optionsCount = 3000,
        dateAwarded = DateTime.Parse("1992/06/30")  },
      new StudentOptionEntry {
        id = 2,
        optionsCount = 3000,
        dateAwarded = DateTime.Parse("1991/01/01")  },
      new StudentOptionEntry {
        id = 3,
        optionsCount = 5000,
        dateAwarded = DateTime.Parse("1997/09/30") },
      new StudentOptionEntry {
        id = 2,
        optionsCount = 3000,
        dateAwarded = DateTime.Parse("2000/04/01")  },
      new StudentOptionEntry {
        id = 3,
        optionsCount = 7500,
        dateAwarded = DateTime.Parse("1998/09/30") },
      new StudentOptionEntry {
        id = 3,
        optionsCount = 7500,
        dateAwarded = DateTime.Parse("1998/09/30") },
      new StudentOptionEntry {
        id = 4,
        optionsCount = 2456,
        dateAwarded = DateTime.Parse("1997/12/31") },
      new StudentOptionEntry {
        id = 101,
        optionsCount = 2,
        dateAwarded = DateTime.Parse("1998/12/31") }
    };

        return (empOptions);
    }
}

Result

Related Topic