LINQ按差异选择日期

huangapple go评论75阅读模式
英文:

LINQ select date by differences

问题

I have an IEnumerable<DateOnly>, how can I filtering from that, or select from the IEnumerable collection those dates which day difference no more than 1 day.

有一个 IEnumerable<DateOnly>,我应该如何从中筛选,或者从这个 IEnumerable 集合中选择那些日期之间的天数差不超过1天的日期。

There are some Dates eg. 05/20/2023, 03/31/1941, 02/02/1965, 03/30/1876, 02/01/1965, 05/21/2023, 12/10/1966, 12/10/1966

例如,有一些日期:05/20/2023,03/31/1941,02/02/1965,03/30/1876,02/01/1965,05/21/2023,12/10/1966,12/10/1966

The expected result is (difference in days no more than 1)

期望的结果是(日期之间的天数差不超过1天)

05/20/2023, 05/21/2023,
02/02/1965, 02/01/1965,
12/10/1966, 12/10/1966

预期结果是(日期之间的天数差不超过1天)

Thank you in advance.

提前感谢。

英文:

I have an IEnumerable<DateOnly>, how can I filtering from that, or select from the IEnumerable collection those dates which day difference no more than 1 day.

There are some Dates eg. 05/20/2023, 03/31/1941, 02/02/1965, 03/30/1876, 02/01/1965, 05/21/2023, 12/10/1966, 12/10/1966

The expected result is (difference in days no more than 1)

05/20/2023, 05/21/2023,   
02/02/1965, 02/01/1965,  
12/10/1966, 12/10/1966

Thank you in advance.

答案1

得分: 1

以下是翻译好的部分:

"You ask for LINQ but that is not your best friend with queries like this, which depend on successors. You will most likely end with a query that is less readable and efficient than a simple (for-)loop solution. But you have asked for it, so here it is:

List<List<DateOnly>> result = dates
    .Select((d, ix) => (Date: d, Index: ix))
    .Select(x => dates
        .Where((d, ix) => x.Index > ix && Math.Abs(x.Date.DayNumber - d.DayNumber) <= 1)
        .Prepend(x.Date)
        .ToList())
    .Where(list => list.Count > 1) // all lists contain at least the single date
    .ToList();"
英文:

You ask for LINQ but that is not your best friend with queries like this, which depend on successors. You will mostl likely end with a query that is less readable and efficient than a simple (for-)loop solution. But you have asked for it, so here it is:

List&lt;List&lt;DateOnly&gt;&gt; result = dates
    .Select((d, ix) =&gt; (Date: d, Index: ix))
    .Select(x =&gt; dates
        .Where((d, ix) =&gt; x.Index &gt; ix &amp;&amp; Math.Abs(x.Date.DayNumber - d.DayNumber) &lt;= 1)
        .Prepend(x.Date)
        .ToList())
    .Where(list =&gt; list.Count &gt; 1) // all lists contain at least the single date
    .ToList();

huangapple
  • 本文由 发表于 2023年5月21日 00:16:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76296169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定