Linq语句查询,可能的组

时间:2018-11-17 22:02:30

标签: c# linq

这一切可以在一个linq语句查询中完成吗?还是应该拨打现有电话,然后进行过滤?

我需要返回即将过期的访问令牌列表。

如果同一applicationName有两个标记。例如“测试3” 然后,如果已经有另一个令牌即将到期,请不要返回该令牌。

因此,根据下面提供的示例,如果我希望所有在15天内到期的令牌,则不应返回任何记录。

cccDDD888将在10天后到期,但eeeFFF999是同一应用程序的新令牌。

            return new List<Domain.Models.AccessToken>
               {
                   new Domain.Models.AccessToken {ApplicationName = "Test", ExpirationDate = DateTime.Now.AddDays(100), Id = new Guid("943e31bd-7c91-44bf-9ee2-3366c9f5010c"), Token = "aaaBBB111"},
                   new Domain.Models.AccessToken {ApplicationName = "Test 2", ExpirationDate = DateTime.Now.AddDays(50), Id = new Guid("cc1cec9b-7de6-46e7-8069-5681c8d2d331"), Token = "xxxYYY777"},
                   new Domain.Models.AccessToken {ApplicationName = "Test 3", ExpirationDate = DateTime.Now.AddDays(10), Id = new Guid("da5343da-e2c4-477c-b3ed-b60133512f5d"), Token = "cccDDD888"},
                   new Domain.Models.AccessToken {ApplicationName = "Test 3", ExpirationDate = DateTime.Now.AddDays(365), Id = new Guid("7d7556d8-e194-43be-89ce-0961fc94ebd4"), Token = "eeeFFF999"},
                   new Domain.Models.AccessToken {ApplicationName = "Test 4", ExpirationDate = DateTime.Now.AddDays(-1), Id = new Guid("0de8a36f-a249-4df1-a5c5-fbaf26e32bb2"), Token = "jjjKKK444"},
               };

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

var allTokens = new List<AccessToken>
    {
        new Domain.Models.AccessToken {ApplicationName = "Test", ExpirationDate = DateTime.Now.AddDays(100), Id = new Guid("943e31bd-7c91-44bf-9ee2-3366c9f5010c"), Token = "aaaBBB111"},
        new Domain.Models.AccessToken {ApplicationName = "Test 2", ExpirationDate = DateTime.Now.AddDays(50), Id = new Guid("cc1cec9b-7de6-46e7-8069-5681c8d2d331"), Token = "xxxYYY777"},
        new Domain.Models.AccessToken {ApplicationName = "Test 3", ExpirationDate = DateTime.Now.AddDays(10), Id = new Guid("da5343da-e2c4-477c-b3ed-b60133512f5d"), Token = "cccDDD888"},
        new Domain.Models.AccessToken {ApplicationName = "Test 3", ExpirationDate = DateTime.Now.AddDays(365), Id = new Guid("7d7556d8-e194-43be-89ce-0961fc94ebd4"), Token = "eeeFFF999"},
        new Domain.Models.AccessToken {ApplicationName = "Test 4", ExpirationDate = DateTime.Now.AddDays(-1), Id = new Guid("0de8a36f-a249-4df1-a5c5-fbaf26e32bb2"), Token = "jjjKKK444"},
    };

var expiringThresholdInDays = 15;
var expirationDeadLine = System.DateTime.Now.AddDays(expiringThresholdInDays);
var expiringTokens = allTokens.GroupBy(a => a.ApplicationName).Where(b => b.OrderByDescending(x => x.ExpirationDate).FirstOrDefault().ExpirationDate < expirationDeadLine);

但是,这将返回Test 4的令牌,该令牌已经过期。如果要排除已经过期的令牌,请将最后一行更改为此:

var expiringTokens = allTokens.GroupBy(a => a.ApplicationName).Where(b =>
{
    var expirationDate = b.OrderByDescending(x => x.ExpirationDate).FirstOrDefault().ExpirationDate;
    return System.DateTime.Now < expirationDate && expirationDate < expirationDeadLine;
});