user1477388 user1477388 - 2 months ago 8
C# Question

C# Instantiate List by Calling a Function

Is there a more minimal way to write the following:

var voucherCodes = new List<string>();

for (int i = 0; i < 10; i++)
{
voucherCodes.Add(GenerateCode(VoucherCodeLength));
}


I would like to do something like this:

// ten items would be added to the list so long as GenerateCode returns a string
var voucherCodes = new List<string>(GenerateCode(VoucherCodeLength), 10);


Granted, I could create my own function, but I was wondering if there was something that already exists.

Answer

I can't say if it's better, but you can use the folloing LINQ "one-liner":

var voucherCodes = Enumerable.Range(0, 10).Select(_ => GenerateCode(VoucherCodeLength)).ToList();

or specifically for this call, and if the VoucherCodeLength is constant (or does not change and has no side effects), an even shorter:

var voucherCodes = Enumerable.Repeat(VoucherCodeLength, 10).Select(GenerateCode).ToList();
Comments