c# - 有没有一种方法可以在 C#/LINQ 中产生、发出或以其他方式实现以前为空的数组?

标签 c# linq

我有一个带有动态字符串数组的对象,我实现如下:

public class MyThing { 
    public int NumberOfThings { get; set; }
    public string _BaseName { get; set; }
    public string[] DynamicStringArray {
        get {
            List<string> dsa = new List<string>();
            for (int i = 1; i <= this.NumberOfThings; i++) {
                dsa.Add(string.Format(this._BaseName, i));
            }
            return dsa.ToArray();
        }
    }
}

我之前试图变得更酷一些,并实现了一些在 LINQ 中自动创建格式化数组列表的东西,但我已经失败了。

作为我正在尝试的事情的一个例子:

int i = 1;
// create a list with a capacity of NumberOfThings
return new List<string>(this.NumberOfThings)
    // create each of the things in the array dynamically
    .Select(x => string.Format(this._BaseName, i++))
    .ToArray();

在这种情况下它真的不是很重要,而且在性能方面它实际上可能更糟,但我想知道是否有一种很酷的方法来在 LINQ 扩展中构建或发出数组。

最佳答案

威尔Range帮助?

return Enumerable
  .Range(1, this.NumberOfThings)
  .Select(x => string.Format(this._BaseName, x))
  .ToArray();

关于c# - 有没有一种方法可以在 C#/LINQ 中产生、发出或以其他方式实现以前为空的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32567641/

相关文章:

c# - LINQ to SQL 和并发问题

c# - 在哪里可以找到类 System.Windows.UIElement

c# - 将局部变量传递给 .net 中的另一个线程

c# - 间歇性 Linq FirstOrDefault 错误 - 索引超出数组范围

c# - 如何仅比较 EF 中 DateTime 的日期组件?

C#:向字典添加数据

C# File.ReadAllLines 不中断换行

c# - Caliburn.Micro - 如何从 Conductor 以外的类激活 Item

c# - F# 声明的命名空间在 c# 项目中不可用或通过对象浏览器可见

asp.net-mvc - 为什么 "linq to sql classes"在创建类时会更改表的名称?