لا يمكن إلحاق قائمة واحدة إلى أخرى في C # ... في محاولة لاستخدام Addrange

StackOverflow https://stackoverflow.com/questions/1724606

سؤال

مرحبا، أحاول إلحاق قائمة بأخرى. لقد فعلت ذلك باستخدام 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()

نصائح أخرى

أود أن أفترض أن .الست () يخلق مجموعة جديدة. لذلك تتم إضافة البنود الخاصة بك إلى مجموعة جديدة يتم إلقاؤها على الفور وظل الأصلي لا يمسه.

resultCollection.ToList() سوف ترجع قائمة جديدة.

يحاول:

List<E> list = resultCollection.ToList();
list.AddRange(resultCollection2);

يحاول

Ilist NewList = engedcollection.tolist (). Addrange (ensegrcolroollection2)؛

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