是否有Linq运算符可确保集合的最小大小
我想看到的是:
int[] x = {1, 2, 3, 4};
var y = x.Fill(6);
// y is now {1, 2, 3, 4, 0, 0}
Run Code Online (Sandbox Code Playgroud)
注意(到目前为止的答案)我正在寻找可以使用的东西IEnumerable<T>. int[]只是为了在示例中轻松初始化
不,但扩展方法并不难:
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);
}
Run Code Online (Sandbox Code Playgroud)
用法:
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}
Run Code Online (Sandbox Code Playgroud)