[英]How to add new Items to an Existing List c#?
我正在上傳一個 Excel 文件,並在閱讀該文件后得到結果。
var data = from c in excel.Worksheet<QuestionMaster>()
select new
{
c.Questionname,
c.Answer1,
c.Answer2,
c.Answer3,
c.Answer4,
c.CorrectAnswer,
};
現在我需要檢查上傳數據中的任何列都不應該為空
為此,我的代碼是:
Question Master是Model類
QuestionMaster questions = new QuestionMaster();
QuestionMaster temp = new QuestionMaster();
List<QuestionMaster> ques = new List<QuestionMaster>();//
foreach (var item in data)
{
int i = 0;
if (item.Questionname == null || item.Answer1 == null || item.Answer2 == null || item.Answer3 == null || item.Answer4 == null || item.CorrectAnswer == null)
{
if (item.Questionname != null)
temp.Questionname = item.Questionname.Trim();
else
temp.Questionname = "Question Name not Found in Uploaded Excel File";
if (item.Answer1 != null)
temp.Answer1 = item.Answer1.Trim();
else
temp.Answer1 = "Answer 1 Not Found in Uploaded Excel File";
\\Some more Couple of If-Else Conditions
ques.Add(temp);
}
現在的問題是:
假設我得到了三個不同的行,其中它們是一些空列並且上述條件成立。
當ques.add(temp)第 2 次或第 3 次運行時,它會覆蓋之前添加的其他列表項,但列表中添加的項數保持不變。
這意味着它正在用temp 中的當前數據覆蓋整個列表。
請告訴我我哪里出錯了。
提前致謝!!!
您每次都需要在循環中創建一個新對象,目前它在您的循環之外,因此原始對象不斷變化
foreach (var item in data)
{
QuestionMaster temp = new QuestionMaster();
}
if (ques.Contains(temp))
{
//todo replace item
}
else
{
ques.Add(temp);
}
並在循環中重新創建引用
您的列表包含 QuestionMaster 的對象:
List<QuestionMaster> ques = new List<QuestionMaster>();
數據列表有匿名類型的對象,嘗試在數據中創建 QuestionMaster 對象而不是任何類型的對象。
試試這個,它會在最后向現有列表添加一個新項目,
列表作者 = 新列表
{
新作者 { Name = "Mahesh Chand", Book = "ADO.NET Programming", Price = 49.95 },
新作者 { Name = "Neel Beniwal", Book = "Jump Ball", Price = 19.95 },
新作者 { Name = "Chris Love", Book = "Practical PWA", Price = 29.95 }
};
// 向列表中添加更多項目
author.Add(new Author { Name = "Mahesh Chand", Book = "Graphics with GDI+", Price = 49.95 });
author.Add(new Author { Name = "Mahesh Chand", Book = "Mastering C#", Price = 54.95 });
author.Add(new Author { Name = "Mahesh Chand", Book = "Jumpstart Blockchain", Price = 44.95 });
關聯
https://www.codegrepper.com/code-examples/csharp/add+object+to+generic+list+c%23
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.