gpt4 book ai didi

c# - LINQ 按日期间隔获取对象

转载 作者:太空宇宙 更新时间:2023-11-03 14:19:48 24 4
gpt4 key购买 nike

我正在寻找一个 LINQ 查询,它将只选择那些日期间隔不超过 20 秒的对象。例如:

AuthenticationEssay[] essays = new AuthenticationEssay[] {
new AuthenticationEssay() { Date = DateTime.Now.AddSeconds(20), Success = false },
new AuthenticationEssay() { Date = DateTime.Now.AddSeconds(24), Success = false },
new AuthenticationEssay() { Date = DateTime.Now.AddSeconds(29), Success = false },
new AuthenticationEssay() { Date = DateTime.Now.AddSeconds(38), Success = false },
new AuthenticationEssay() { Date = DateTime.Now.AddSeconds(125), Success = false },
new AuthenticationEssay() { Date = DateTime.Now.AddSeconds(347), Success = false },
new AuthenticationEssay() { Date = DateTime.Now.AddSeconds(400), Success = false },
new AuthenticationEssay() { Date = DateTime.Now.AddSeconds(422), Success = false },
new AuthenticationEssay() { Date = DateTime.Now.AddSeconds(446), Success = false },
new AuthenticationEssay() { Date = DateTime.Now.AddSeconds(467), Success = false }
};

我只想选择那些日期间隔不超过 20 秒的对象中第一次出现的对象。在这种情况下,查询应该只返回前 4 个对象。任何想法? :(

更新

抱歉,我忘了说我是按降序对数组进行排序的。所以是的,数组中的位置不应该对查询有任何影响。

最佳答案

这个呢?

var query from i in Enumerable.Range(1, count - 1)
let current = list[i]
let previous = list[i - 1]
// I see some empty positions in your example, nullability check
where current != null && previous != null
where (current.Date - previous.Date).TotalSeconds < 20
select previous;

编辑:显然,您必须调用 First() 才能仅获取序列的第一个元素。

query.First();

编辑 2: 我刚刚了解到您正在对结果进行降序排序。在这种情况下,查询会略有不同:

var query from i in Enumerable.Range(1, count - 1)
let current = list[i]
let previous = list[i - 1]
// I see some empty positions in your example, nullability check
where current != null && previous != null
where (previous.Date - current.Date).TotalSeconds < 20
select current;

关于c# - LINQ 按日期间隔获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5688833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com