Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more succinct Linq expression for inserting a constant between every item in a list?

Tags:

c#

linq

Here's what I have at the moment:

public List<double> GetStrokeDashArray(List<double> dashLengths, double gap)
{
    return dashLengths
        .SelectMany(dl => new[] { dl, gap })
        .Take(dashLengths.Count * 2 - 1)
        .ToList();
}

Results for GetStrokeDashArray(new List<double> { 2, 4, 7, 11, 16 }, 2);

2, 2, 4, 2, 7, 2, 11, 2, 16
like image 242
devuxer Avatar asked Dec 17 '22 02:12

devuxer


1 Answers

I think the best way is to create a specific extension method for that:

public static IEnumerable<T> Intersperse<T>(this IEnumerable<T> source, T value)
{
    bool first = true;
    foreach(T item in source)
    {
        if (!first) yield return value;
        yield return item;
        first = false;
    }
}

You can then write your method as follows:

public List<double> GetStrokeDashArray(List<double> dashLengths, double gap)
{
    return dashLengths
        .Intersperse(gap)
        .ToList();
}
like image 104
Thomas Levesque Avatar answered Dec 28 '22 23:12

Thomas Levesque