2017-06-07 6 views
1

私は連結したい2つのList<Student>を持っています。リストを追加するには<Class>をC#で一緒に追加しますか?

Studentは、いくつかのプロパティを含む単なるクラスです。 StudentCreatorが閉じるとき

は私もStudentを作成し、そこからList<Student>

を移入する別のFormを持って、私はStudentCreatorList<Student>がメインフォームでList<Student>にconcatedことにしたいです。効果的にメインリストを更新します。

これは私が、私はこれはエラーに

を与えるメインラインであるいくつかの 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) 

このエラーを解決するにはどうすればよいですか?

+0

コール 'tempList.Concat(tempList).ToList()'(あなたが連結されていることに注意してください途中で同じリストを参照してください)。 – Evk

+0

うん、私はそれに感謝しています:) – Dave

答えて

5

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); 
関連する問題