Search code examples
c#asp.netasp.net-mvc-5

How to get oldest date from collection list using but based on other clauses LINQ


I have the following code:

MostRecentLogonList.Add(new LastLogons
{
    Id = id++,
    FirstName = FirstName,
    MiddleInitial = MiddleInitial,
    LastName = LastName,
    SAMAccountName = samaccountName,
    DistinguishedName = distinguishedName,
    OU = organizationalUnit,
    dnsHost = dnsHostName,
    lastLogon = lastLogon
});

InactiveList = InactiveList
   .Where(l => l.lastLogon <= CurrentDate.AddDays(-filterDays))
   .GroupBy(s => s.SAMAccountName)
   .Select(scope => scope.OrderBy(l => l.lastLogon).Last()).ToList();

"filterDays" is from an input field, set to 90. What I am trying to do is display a list of users who have not logged in for the past 90+ days across 3 domain controllers. The above gives me the output of:

SAMAccountName    LastLogon      DomainController
test.user1        12/31/1600     dc02
test.user2        12/31/1600     dc02
test.user5        12/31/1600     dc01
test.user4        12/31/1600     dc03

Problem that I am having is, "test.user1" has a LastLogon of 9/30/2020 on "dc01" and "test.user4" has a LastLogon of 10/4/2020 on "dc01" as well, therefore, I do not want it to show up at all in the inactivity list.

I'm assuming I have to add something additional in the where clause but not sure exactly how to translate this:

"if a samaccount name has a LastLogon date less than or equal to the current date minus 90 days on dc01 but also has a LastLogon date greater than 90 days on since it logged into dc02, don't display it."


Solution

  • You are almost there. Just need to make small change. You should apply GroupBy & Select lastLogon record and then use Where to filter. Try it like below.

    InactiveList = InactiveList
       .GroupBy(s => s.SAMAccountName)
       .Select(scope => scope.OrderBy(l => l.lastLogon).Last())
       .Where(l => l.lastLogon <= CurrentDate.AddDays(-filterDays))
       .ToList();
    

    Edit

    https://dotnetfiddle.net/7M396o here is a fiddle. Created small demo with required property only. You can see that with old code it will return 2 records while new code returns only one.