How to group array of dates into multiple pairs in c#?
This can be done using the LINQ Aggregate method but it's easier to use the MoreLINQ Pairwise operator:
var dates=new []{
new DateTime(2021,9,30),
...
};
var pairs=dates.Pairwise((a,b)=new {Start=a,End=b});
foreach(var pair in pairs)
{
var start=pair.Start;
...
}
You can use tuples instead of anonymous types to reduce allocations:
var pairs=dates.Pairwise((a,b)=(Start:a,End:b));
foreach(var pair in pairs)
{
var start=pair.Start;
...
}
Pairwise
is a small function. You could add it directly to your code instead of installing the MoreLINQ package:
public static IEnumerable<TResult> Pairwise<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TSource, TResult> resultSelector)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector));
return _(); IEnumerable<TResult> _()
{
using var e = source.GetEnumerator();
if (!e.MoveNext())
yield break;
var previous = e.Current;
while (e.MoveNext())
{
yield return resultSelector(previous, e.Current);
previous = e.Current;
}
}
}
Using Zip
Another option is to use Enumerable.Zip to combine the array with itself after skipping one element:
var pairs=dates.Zip(dates.Skip(1),(a,b)=>(Start:a,Start:b));
foreach(var pair in pairs)
{
var start=pair.Start;
...
}