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

Matt picture Matt · Nov 12, 2009 · Viewed 11.7k times · Source

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

Answer

Greg Beech picture Greg Beech · Nov 12, 2009

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()