英文:
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<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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论