简体   繁体   English

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

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

I have two List<Student> that I want to concat. 我有两个想要合并的List<Student>

Student is just a class that contains a few properties. Student只是一个包含一些属性的课程。

I also have another Form that creates the Student and populates a List<Student> 我还有另一个创建Student并填充List<Student> Form

From there, when the StudentCreator closes, I want the List<Student> in StudentCreator to be concated to the List<Student> in the main form. 从那里开始,当StudentCreator关闭时,我希望将StudentCreatorList<Student> StudentCreator为主窗体中的List<Student> Effectively updating the main list. 有效地更新主列表。

This is the main bit of code I'm having trouble with, I get an error saying I can't convert some IEnumerable<something> to List<something> 这是我遇到麻烦的主要代码,我收到一条错误消息,说我无法将某些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);
            }
        }

This is the main line that gives the error 这是产生错误的主线

tempList.Concat(tempList)

How do I fix this error? 如何解决此错误?

tempList.Concat returns an enumerable, something you can iterate over. tempList.Concat返回一个可枚举的东西,您可以对其进行迭代。 If you want to transform that into a list, you can call ToList() : 如果要将其转换为列表,可以调用ToList()

var newList = tempList.Concat(tempList).ToList();
// you are basically copying the same list... is this intentional?

Another approach you could take is creating a new list, iterate over the existing lists and add them to the newly created list: 您可以采用的另一种方法是创建一个新列表,遍历现有列表并将它们添加到新创建的列表中:

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