views:

581

answers:

5

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

+3  A: 

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.

Quibblesome
If I try making it get returned into a new list it says. "cannot implicitly convert type 'void' to 'System.Collection.Generic.List<E>'" so my guess is it's not returning anything?
Matt
The same mistake I made! AddRange returns void.
Philip Wallace
Use the solution offered by Greg Beech. Also, if accepting go for him rather than me, i've only pointed out the problem, he's done that plus provided a solution! :)
Quibblesome
A: 

resultCollection.ToList() will return a new list.

Try:

List<E> list = resultCollection.ToList();
list.AddRange(resultCollection2);
Philip Wallace
`AddRange` returns void.
280Z28
Well spotted... fixed.
Philip Wallace
+1  A: 

Try

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

List<E> newList = resultCollection.ToList();
newList.AddRange(resultCollection2);
Justin Niessner
+13  A: 

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()
Greg Beech
Awesome, worked perfectly, thanks!
Matt
A: 

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));
280Z28