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
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With