我有一个带有动态字符串数组的对象,我实现如下:
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/