AddRangeを使用しようと... C#で別のリストを追加することはできません
-
19-09-2019 - |
質問
こんにちは、私は別の1つのリストを追加しようとしています。私は前にAddRange()
を使用してそれをやったが、それはここで動作していないようです...ここでは、コードです。
IList<E> resultCollection = ((IRepository<E, C>)this).SelectAll(columnName, maxId - startId + 1, startId);
IList<E> resultCollection2 = ((IRepository<E, C>)this).SelectAll(columnName, endId - minId + 1, minId);
resultCollection.ToList().AddRange(resultCollection2);
私は結果を確認するために、デバッグをした、ここで私が得たものだ:resultCollection
は4 resultCollection2
の数が6の数を持っており、範囲を追加した後、resultCollection
はまだわずか4の数を持っている、それは数を持っている必要がある場合10のます。
誰も私が間違ってやっているかを見ることができますか?すべてのヘルプは高く評価されます。
おかげで、
マット
解決
あなたが
ToList()
を呼び出すと、あなたはそれで同じ項目で新しいList<T>
を作成しているList<T>
でコレクションをラップされていません。それでは、あなたが効果的にここでやっていることは、新しいリストを作成し、それに項目を追加して、離れリストを投げされます。
あなたのような何かをする必要があると思います:
List<E> merged = new List<E>();
merged.AddRange(resultCollection);
merged.AddRange(resultCollection2);
あなたがC#3.0を使用している場合は、あるいは、単に例えば、Concat
を使用します。
resultCollection.Concat(resultCollection2); // and optionally .ToList()
他のヒント
私は、新しいコレクションを作成している)(.ToListを引き受けます。したがって、あなたのアイテムがすぐに捨てられ、新しいコレクションに追加され、元はそのまま残ります。
resultCollection.ToList()
が新しいリストを返します。
試します:
List<E> list = resultCollection.ToList();
list.AddRange(resultCollection2);
試してみてください。
<ストライキ> IList newList = resultCollection.ToList()AddRange(resultCollection2)。 ストライキ>
List<E> newList = resultCollection.ToList();
newList.AddRange(resultCollection2);
次のいずれかを使用することができます:
List<E> list = resultCollection as List<E>;
if (list == null)
list = new List<E>(resultCollection);
list.AddRange(resultCollection2);
それともます:
// Edit: this one could be done with LINQ, but there's no reason to limit
// yourself to .NET 3.5 when this is just as short.
List<E> list = new List<E>(resultCollection);
list.AddRange(resultCollection2);
それともます:
List<E> list = new List<E>(resultCollection.Concat(resultCollection2));
所属していません StackOverflow