質問

こんにちは、私は別の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));
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top