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

I have an object with a dynamic array of strings, which I 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 tried to be a little colder before and implement something that automatically created a formatted list of arrays in LINQ, but I managed to fail.

As an example of what I tried:

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();

In this case, it really is not that important, and it might be worse in performance, but I was wondering if there is a cool way to create or emit an array in LINQ extensions.

+4
source share
3 answers

Will Range Help?

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

IEnumerable, ToArray(), .

public string[] DynamicStringArray
{
    get
    {
        for (int i=1; i <= this.NumberOfThings; i++)
            yield return string.Format(this._BaseName, i);
    }
}

- . :

public string[] DynamicStringArray
{
    get
    {
        string[] result = new string[this.NumberOfThings];
        for (int i = 0; i < this.NumberOfThings; i++)
        {
            result[i] = string.Format(this._BaseName, i + 1));
        }
        return result;
    }
}

Linq , . , , .

+1

I would revise the existing solution a bit:

  public class MyThing { 
    ...

    // Note IEnumerable<String> instead of String[]
    public IEnumerable<String> DynamicString(int numberOfThings) {
      if (numberOfThings < 0)
        throw new ArgumentOutOfRangeException("numberOfThings");

      for (int i = 0; i < numberOfThings; ++i)
        yield return string.Format(this._BaseName, i + 1);
    } 
  }

whenever you want, say, an array, you can easily get it:

  MyThing thing = ...;
  // Add .ToArray() to have an array
  String[] myArray = thing.DynamicString(18).ToArray();

but whenever you only want a loop, there is no need to create an array or list (materialize the result)

  // no materialization: no array of 1000000 items
  foreach (String item in thing.DynamicString(1000000)) {
    ...
  }
+1
source

Source: https://habr.com/ru/post/1607289/


All Articles