如何使用但基于 LINQ 的其他子句从集合列表中获取最早的日期

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

我有以下代码:

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”来自输入字段,设置为 90。我想做的是显示过去 90 多天未在 3 个域控制器上登录的用户列表。上面给了我输出:

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

我遇到的问题是,“test.user1”在“dc01”上的 LastLogon 为 9/30/2020,而“test.user4”的 LastLogon 为 10/ 4/2020 也在“dc01”上,因此,我根本不希望它出现在不活动列表中。

我假设我必须在 where 子句中添加一些额外的东西,但不确定如何翻译它:

"如果 samaccount 名称的 LastLogon 日期小于或等于 dc01 上的当前日期减去 90 天,但也有一个自登录后大于 90 天的 LastLogon 日期dc02,不要显示它。"

你快到了。只需要做一些小改动。您应该应用 GroupBy & Select lastLogon 记录,然后使用 Where 进行过滤。像下面这样尝试。

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

编辑

https://dotnetfiddle.net/7M396o这里是一个fiddle。创建了仅需要 属性 的小型演示。您可以看到,使用旧代码它将 return 2 条记录,而新代码 return 只有一条。