Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq fill function

Tags:

c#

linq

Is there a Linq operator that will ensure that a collection is a minimum size

What I would like to see is:

int[] x = {1, 2, 3, 4};
var y = x.Fill(6);

// y is now {1, 2, 3, 4, 0, 0}

Note (from the answers so far) I'm looking for something that will work with IEnumerable<T>. int[] was just for easy initialization in the example

like image 465
Jeff Hornby Avatar asked Dec 07 '22 03:12

Jeff Hornby


1 Answers

No, but an extension method wouldn't be hard:

public static IEnumerable<T> PadRight<T>(this IEnumerable<T> source, int length)
{
    int i = 0;
    // use "Take" in case "length" is smaller than the source's length.
    foreach(var item in source.Take(length)) 
    {
       yield return item;
       i++;
    }
    for( ; i < length; i++)
        yield return default(T);
}

Usage:

int[] x = {1, 2, 3, 4};
var y = x.PadRight(6);

// y is now {1, 2, 3, 4, 0, 0}

y = x.PadRight(3);

// y is now {1, 2, 3}
like image 133
D Stanley Avatar answered Dec 10 '22 11:12

D Stanley