我有一个包含多个 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/