Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to yield, emit or otherwise materialize a previously empty array in C# / LINQ?

Tags:

c#

linq

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.

like image 779
Alex C Avatar asked Dec 11 '22 21:12

Alex C


1 Answers

Will Range help?

return Enumerable
  .Range(1, this.NumberOfThings)
  .Select(x => string.Format(this._BaseName, x))
  .ToArray();
like image 83
Backs Avatar answered Feb 08 '23 23:02

Backs