c# - 如何将列表添加到 C# 中的另一个列表?

标签 c# list itemssource

我有一个包含多个 listViews 的页面。我已经从 DbModels 创建了一些差异列表,并且需要将这些列表绑定(bind)到 ListViews。这里我想要的是 if (Particulars == Constants.TAG_OPENING_STOCK) 一个列表添加到一个 ItemsTradingDebitList 列表。

if(Particulars == Constants.TAG_PURCHASE) 另一个列表应该添加到ItemsTradingCreditList 列表。

我已经尝试创建一个包含值的新列表,并使用 AddRange 将其添加到另一个列表。但这会带来错误 Object Reference not set to an instance of an object. list was empty

if (Particulars == Constants.TAG_OPENING_STOCK)
{
    List<string> NewList = new List<string> { Particulars, Amount };
    ItemsTradingDebitList.AddRange(NewList);              
}
if(Particulars == Constants.TAG_PURCHASE)
{
    List<string> NewList = new List<string> { Particulars, Amount };
    ItemsTradingDebitList.AddRange(NewList);
}
if(Particulars == Constants.TAG_SALES)
{
    List<string> NewList = new List<string> { Particulars, Amount };
    ItemsTradingCreditList.AddRange(NewList);
}

我的预期结果是所有添加列表的列表。我得到的是一个错误

最佳答案

我相信"Particulars", "Amount"都是字符串,如果都是字符串,那么你可以直接把它添加到列表中,这里不需要创建新的列表

有点像,

ItemsTradingDebitList.Add("Amount");    
ItemsTradingDebitList.Add("Particulars");   

根据问题中提到的错误,我猜你还没有初始化列表,即 ItemsTradingDebitList。如果是这样,那么在第一个 if 条件创建 ItemsTradingDebitList

实例之前

喜欢

List<string> ItemsTradingDebitList = new List<string>();

这将解决您的问题,

List<string> ItemsTradingDebitList = new List<string>(); //This might be missing in your code
if (Particulars == Constants.TAG_OPENING_STOCK)
{
    ItemsTradingDebitList.Add("Amount");    
    ItemsTradingDebitList.Add("Particulars");   
}
if(Particulars == Constants.TAG_PURCHASE)
{
    ItemsTradingDebitList.Add("Amount");    
    ItemsTradingDebitList.Add("Particulars"); 
}
if(Particulars == Constants.TAG_SALES)
{
    ItemsTradingDebitList.Add("Amount");    
    ItemsTradingDebitList.Add("Particulars"); 
}

关于c# - 如何将列表添加到 C# 中的另一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56182489/

相关文章:

c# - 如果预先知道订阅者,我应该使用观察者模式吗?

C#:继承、覆盖和隐藏

c# - Polly 重试除特定条件外的所有异常

python - 按第三个元素排序 Python 列表,然后按第一个元素,等等?

wpf - ItemContainerGenerator.ContainerFromItem() 返回 null?

c# - 在 WPF DataGrid 上显示行号的简单方法

c# - 将列表添加到 ObjectListView 时出现异常

wpf - 带有 MVVM 的 WPF 中的 COMBOBOX 过滤

wpf - IsSynchronizedWithCurrentItem 属性和当前项目更新

python - 创建字典,其中列表项作为键,列表项出现的次数作为值