简体   繁体   中英

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

I have two List<Student> that I want to concat.

Student is just a class that contains a few properties.

I also have another Form that creates the Student and populates a List<Student>

From there, when the StudentCreator closes, I want the List<Student> in StudentCreator to be concated to the List<Student> in the main form. 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>

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. If you want to transform that into a list, you can call 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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