I have an object with a dynamic array of strings which I've implemented as follows:
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();
}
}
}
I was trying to be a little cooler earlier and implement something that autocreated the formatted list of arrays in LINQ but I've managed to fail.
As an example of the thing I was trying:
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();
It's really not terribly important in this case, and performance-wise it might actually be worse, but I was wondering if there was a cool way to build or emit an array in LINQ extensions.
Will Range help?
return Enumerable
.Range(1, this.NumberOfThings)
.Select(x => string.Format(this._BaseName, x))
.ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With