-3

Is it possible to combine the two Add statements below into one statement? Each adds an object to a list (accountTypeOptions)

accountTypeOptions.Add(new()
{
    Text = "Easy Access",
    Value = BankAccountType.EasyAccess.ToString()
});

accountTypeOptions.Add(new()
{
    Text = "Fixed Term",
    Value = BankAccountType.FixedTerm.ToString()
});
Musaffar Patel
  • 905
  • 11
  • 26
  • 1
    You could do `AddRange(new[] {new() {...}, new() {...}})` but that creates a temporary array that just gets thrown away. – juharr Mar 08 '23 at 19:13
  • Thanks, this is what a certain AI suggested but it produces a syntax error. No a huge problem, just wondered if there was already a syntax available for this type of thing – Musaffar Patel Mar 08 '23 at 19:16

1 Answers1

1

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.

David L
  • 32,885
  • 8
  • 62
  • 93
  • Thanks for going the extra length with the extension example. Am I correct in understanding that multiple items may only be combined into a single statement during the initialisation of the list? – Musaffar Patel Mar 08 '23 at 19:22
  • 1
    @MusaffarPatel I updated my answer. It's syntactic sugar that the compiler provides that merely calls .Add multiple times behind the scenes. If you already have a collection, you can call .AddRange instead. – David L Mar 08 '23 at 19:29
  • Collection initialization works with any class that implements `IEnumerable` (generic or not) and has one or more `Add` methods with a signature like `void Add(SomeType obj, [SomeTypeN objN]...)` – Flydog57 Mar 08 '23 at 19:55