[英]How to add two List<Class> together in c#?
我有兩個想要合並的List<Student>
。
Student
只是一個包含一些屬性的課程。
我還有另一個創建Student
並填充List<Student>
Form
從那里開始,當StudentCreator
關閉時,我希望將StudentCreator
的List<Student>
StudentCreator
為主窗體中的List<Student>
。 有效地更新主列表。
這是我遇到麻煩的主要代碼,我收到一條錯誤消息,說我無法將某些IEnumerable<something>
轉換為List<something>
private void update_students(addStudent s)
{
Form activeForm = Form.ActiveForm;
if(activeForm == this)
{
tempList = s.StudentList;
studentList_HomeForm = tempList.Concat(tempList);
}
}
這是產生錯誤的主線
tempList.Concat(tempList)
如何解決此錯誤?
tempList.Concat
返回一個可枚舉的東西,您可以對其進行迭代。 如果要將其轉換為列表,可以調用ToList()
:
var newList = tempList.Concat(tempList).ToList();
// you are basically copying the same list... is this intentional?
您可以采用的另一種方法是創建一個新列表,遍歷現有列表並將它們添加到新創建的列表中:
List<Student> newList = new List<Student>(firstList); // start of by copying list 1
// Add every item from list 2, one by one
foreach (Student s in secondList)
{
newList.Add(s);
}
// Add every item from list 2, at once
newList.AddRange(secondList);
您可以使用AddRange方法-https://msdn.microsoft.com/zh-cn/library/z883w3dc( v= vs.110).aspx
studentList.AddRange(tempList);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.