There is no built-in method to do this, although if you use a collection initializer when instantiating the list, you can minimize the typing:
var accountTypeOptions = new List<AccountTypeOption>
{
new()
{
Text = "Easy Access",
Value = BankAccountType.EasyAccess.ToString()
}),
new()
{
Text = "Fixed Term",
Value = BankAccountType.FixedTerm.ToString()
}
};
Note that collection initializers are simply syntactic sugar for abstracting away multiple calls to .Add()
. The following:
var list = new List<string>()
{
"one",
"two"
};
compiles to:
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
That said, nothing prevents you from creating an extension method for this behavior:
public static class ListExtensions
{
public static void Add<T>(this List<T> list, params T[] itemsToAdd)
{
foreach (var item in itemsToAdd)
{
list.Add(item);
}
}
}
This can be used as follows:
var list = new List<string>();
list.Add("one", "two");
Note that using params does generate a backing array for the passed arguments which is less efficient, but if this isn't a hot path, it may be acceptable.