user1477388 user1477388 - 1 year ago 67
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++)

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 Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download