Home | Feedback | Login

Group by Linq vs Lambda

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

namespace WDSConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {

            List<StaffActionHistory> history = new List<StaffActionHistory>()
            {
                 new StaffActionHistory() { LogId = 1, PIN = "123", ReasonCode = "xxx" },
                 new StaffActionHistory() { LogId = 2, PIN = "123", ReasonCode = "xxx" },
                 new StaffActionHistory() { LogId = 3, PIN = "1234", ReasonCode = "xxx1" },
                 new StaffActionHistory() { LogId = 4, PIN = "1234", ReasonCode = "xxx1" },
                 new StaffActionHistory() { LogId = 5, PIN = "1234", ReasonCode = "xxx1" }
            };                    

            // group by with linq
            var result2 = from hist in history
                         group hist by new { hist.ReasonCode, hist.PIN } into g
                         select new StaffActionHistory
                         { LogId = g.Max(i => i.LogId), PIN = g.Key.PIN, ReasonCode = g.Key.ReasonCode  };

            // group by with lambda
            var result3 = history
                        .GroupBy(hist => new { hist.ReasonCode, hist.PIN })
                        .Select(g => new StaffActionHistory
                        { LogId = g.Max(i => i.LogId), PIN = g.Key.PIN, ReasonCode = g.Key.ReasonCode } );
            
            foreach(StaffActionHistory r in result2 )
            {
                Console.WriteLine("Id: " + r.LogId + " PIN:  " + r.PIN + "ReasonCode: " +r.ReasonCode );
            }     

            Console.ReadLine();    

       
        }
    }
}