繁体   English   中英

如何添加两个列表 <Class> 一起在C#中?

[英]How to add two List<Class> together in c#?

我有两个想要合并的List<Student>

Student只是一个包含一些属性的课程。

我还有另一个创建Student并填充List<Student> Form

从那里开始,当StudentCreator关闭时,我希望将StudentCreatorList<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM