Search code examples
c#linqselectfilter

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.

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.


Solution

  • 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();