title: Can C# Collection Initializers accept a lambda generator or only fixed values
body: <p>This is kind of a duplicate of <a href="https://stackoverflow.com/questions/1402860/c-using-lambdas-with-collection-initialization">c#, using lambdas with collection initialization</a>, but its 13 odd years old and things have changed. Hopefully.</p>
  <p>I'm writing a one off unit test, so I'm not looking for extension methods or something that requires lots of supporting code. I could probably have written the code in less time than this question takes, but now I'm curious and my Google-fu hasn't turned up anything useful/recent. A yes (and how)/no answer would suffice initially and reasons can follow later.</p>
  <p>The MS docs on collection initializers indicate in one of their examples that you can use a method to return a single value. BUT, what about a collection instead? no mention. There is a (closed) 7 year old <a href="https://github.com/dotnet/roslyn/issues/963" rel="nofollow noreferrer">feature request</a> for Roslyn which was never implemented, and now has dead links, that is similar to what I'm thinking.</p>
  <p>How to do something like this <em>without</em> writing another function in the test class:</p>
  <pre><code>ClassA instanceA = new ClassA {
      MyListB = new List&lt;ClassC&gt;() { 
          () =&gt; { 
             List&lt;ClassC&gt; list = new List&lt;ClassC&gt;();
             for(int i = 0; i &lt; 10; i++)
                 list.add(new ClassC() {SomeProp = i});
             return list;
           }
      }
  }
  </code></pre>
  <p>I suppose the extra nesting level is irrelevant for the question, it just matches my current structure.</p>
  <p>I know I can write</p>
  <pre><code>List&lt;ClassC&gt; GetList() {
      List&lt;ClassC&gt; list = new List&lt;ClassC&gt;();
      for(int i = 0; i &lt; 10; i++)
         list.add(new ClassC() {SomeProp = i});
      return list;
  }
  
  ClassA instanceA = new ClassA {
      MyListB = GetList()
  }
  </code></pre>
  <p>Just curious as to if there is a different (more lazy?) way?</p>
  <p>I'm using VS2022, the test project is xUnit using .Net Core 6, and the system under test is a .Net 4.6.1 dll project. Language version ranges through the various projects. It's irritating, but I'm working on it, I'm a new starter to an established solution.</p>