c# - Linq 填充函数

标签 c# linq

是否有 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/

相关文章:

C# LINQ Orderby - 真/假如何影响 orderby?

c# - 错误绑定(bind) Gridview : "The current TransactionScope is already complete"

c# - Asp.Net WebApi 继承与 BaseController

C# - 在对象初始化器中使用值两次

c# - 可枚举或列表的属性

c# - Linq 查询获取对象列表并为每个对象获取另一个嵌套列表

c# - 使用 ImpromptuInterface 调用基类的私有(private)成员

c# - 有没有办法检查是否所有定义的函数都被调用?

c# - 当鼠标从列表框移开时,列表框上的多项选择不起作用

c# - 具有相同命名空间但在不同程序集中的内部类?