将两个 Add 语句合并为一个?

问题描述 投票:0回答:1

是否可以将下面的两个 Add 语句合并为一个语句?每个都将一个对象添加到列表中(accountTypeOptions)

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

accountTypeOptions.Add(new()
{
    Text = "Fixed Term",
    Value = BankAccountType.FixedTerm.ToString()
});
c# asp.net-core .net-core
1个回答
1
投票

没有内置方法可以做到这一点,但如果在实例化列表时使用集合初始化程序,则可以最大限度地减少输入:

var accountTypeOptions = new List<AccountTypeOption>
{
    new()
    {
        Text = "Easy Access",
        Value = BankAccountType.EasyAccess.ToString()
    }),
    new()
    {
        Text = "Fixed Term",
        Value = BankAccountType.FixedTerm.ToString()
    }

};

就是说,没有什么能阻止您为此行为创建扩展方法:

public static class ListExtensions
{
    public static void Add<T>(this List<T> list, params T[] itemsToAdd)
    {
        foreach (var item in itemsToAdd)
        {
            list.Add(item);
        }
    }
}

可以这样使用:

var list = new List<string>();
list.Add("one", "two");

请注意,使用 params 确实会为传递的参数生成一个效率较低的支持数组,但如果这不是热路径,它可能是可以接受的。

© www.soinside.com 2019 - 2024. All rights reserved.