开发者

Can't append one list to another in C#... trying to use AddRange

开发者 https://www.devze.com 2022-12-11 11:42 出处:网络
Hi I\'m trying to append 1 list to another. I\'ve done it using AddRange() before but it doesn\'t seem to be working here... Here\'s the code:

Hi I'm trying to append 1 list to another. I've done it using AddRange() before but it doesn't seem to be working here... Here's the code:

IList<E> resultCollection = ((IRepository<E, C>开发者_如何学Go;)this).SelectAll(columnName, maxId - startId + 1, startId);                
IList<E> resultCollection2 = ((IRepository<E, C>)this).SelectAll(columnName, endId - minId + 1, minId);
resultCollection.ToList().AddRange(resultCollection2);

I did debugging to check the results, here's what I got: resultCollection has a count of 4 resultCollection2 has a count of 6, and after adding the range, resultCollection still only has a count of 4, when it should have a count of 10.

Can anyone see what I'm doing wrong? Any help is appreciated.

Thanks,

Matt


When you call ToList() you aren't wrapping the collection in a List<T> you're creating a new List<T> with the same items in it. So what you're effectively doing here is creating a new list, adding the items to it, and then throwing the list away.

You'd need to do something like:

List<E> merged = new List<E>();
merged.AddRange(resultCollection);
merged.AddRange(resultCollection2);

Alternatively, if you're using C# 3.0, simply use Concat, e.g.

resultCollection.Concat(resultCollection2); // and optionally .ToList()


I would assume .ToList() is creating a new collection. Therefore your items are being added to a new collection that is immediately thrown away and the original remains untouched.


resultCollection.ToList() will return a new list.

Try:

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


Try

IList newList = resultCollection.ToList().AddRange(resultCollection2);

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


You can use any of the following:

List<E> list = resultCollection as List<E>;
if (list == null)
    list = new List<E>(resultCollection);
list.AddRange(resultCollection2);

Or:

// 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);

Or:

List<E> list = new List<E>(resultCollection.Concat(resultCollection2));
0

精彩评论

暂无评论...
验证码 换一张
取 消