是否有 Linq 运算符可以确保集合的大小最小
我想看到的是:
int[] x = {1, 2, 3, 4};
var y = x.Fill(6);
// y is now {1, 2, 3, 4, 0, 0}
注意(从到目前为止的答案中)我正在寻找可以与
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);
}
用法:
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}
关于c# - Linq 填充函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22152160/