I have a method which takes in N, the number of objects I want to create, and I need to return a list of N objects.
Currently I can do this with a simple loop:
You can use the Range
to create a sequence:
return Enumerable.Range(0, count).Select(x => new MyObj { bar = foo });
If you want to create a List
, you'd have to ToList
it.
Mind you though, it's (arguably) a non-obvious solution, so don't throw out the iterative way of creating the list just yet.
You can Use Enumerable.Repeat
IEnumerable<MyObject> listOfMyObjetcs = Enumerable.Repeat(CreateMyObject, numberOfObjects);
For more info read https://msdn.microsoft.com/en-us/library/bb348899(v=vs.110).aspx
You could create generic helper methods, like so:
// Func<int, T>: The int parameter will be the index of each element being created.
public static IEnumerable<T> CreateSequence<T>(Func<int, T> elementCreator, int count)
{
if (elementCreator == null)
throw new ArgumentNullException("elementCreator");
for (int i = 0; i < count; ++i)
yield return (elementCreator(i));
}
public static IEnumerable<T> CreateSequence<T>(Func<T> elementCreator, int count)
{
if (elementCreator == null)
throw new ArgumentNullException("elementCreator");
for (int i = 0; i < count; ++i)
yield return (elementCreator());
}
Then you could use them like this:
int count = 100;
var strList = CreateSequence(index => index.ToString(), count).ToList();
string foo = "foo";
var myList = CreateSequence(() => new MyObj{ Bar = foo }, count).ToList();