I'm creating a method that expands a sequence.
This is a sample of how it works:
Input: {1, 2, 3}
Output: {1}, {1, 2}, {1,2,3}
So far, I've been able to solve the algorithm using 2 different approaches:
Approach 1
public IEnumerable<IEnumerable<T>> Expand<T>(IEnumerable<T> sequence)
{
return sequence.Select((x, i) => sequence.Take(i + 1));
}
Approach 2
Using Aggregate
public IEnumerable<IEnumerable<T>> Expand<T>(IEnumerable<T> sequence)
{
return sequence.Aggregate(new List<List<T>>(), (a, i) =>
{
var prev = a.LastOrDefault() ?? Enumerable.Empty<T>();
var newList = prev.Concat(new[] { i });
var sources = newList.ToList();
return a.Concat(new[] { sources }).ToList();
});
}
This one is overly complicated. But it works.
Is there a more elegant way to do this using LINQ or its extension methods?