using System.Collections.Generic;
public int id { get; set; }
public string SAMAccountName { get; set; }
public DateTime lastLogon { get; set; }
public static void Main()
var InactiveList = new List<LastLogons>()
new LastLogons() { id = 1, SAMAccountName = "test.user1", lastLogon = DateTime.Now.AddDays(-10) },
new LastLogons() { id = 1, SAMAccountName = "test.user1", lastLogon = DateTime.Now.AddDays(-100) },
new LastLogons() { id = 2, SAMAccountName = "test.user2", lastLogon = DateTime.Now.AddDays(-100) },
new LastLogons() { id = 2, SAMAccountName = "test.user2", lastLogon = DateTime.Now.AddDays(-1000) },
DateTime CurrentDate = DateTime.Now;
var result1 = InactiveList
.Where(l => l.lastLogon <= CurrentDate.AddDays(-filterDays))
.GroupBy(s => s.SAMAccountName)
.Select(scope => scope.OrderBy(l => l.lastLogon).Last())
var result2 = InactiveList
.GroupBy(s => s.SAMAccountName)
.Select(scope => scope.OrderBy(l => l.lastLogon).Last())
.Where(l => l.lastLogon <= CurrentDate.AddDays(-filterDays))
Console.WriteLine("Result count with old code - " + result1.Count());
Console.WriteLine("Result count with new code - " + result2.Count());