.NET List Concat vs AddRange

Go To StackoverFlow.com

73

What is the difference between the AddRange and Concat functions on a generic List? Is one recommended over the other?

2008-09-19 07:14
by johnc


101

They have totally different semantics.

AddRange modifies the list by adding the other items to it.

Concat returns a new sequence containing the list and the other items, without modifying the list.

Choose whichever one has the semantics you want.

2008-09-19 07:17
by Greg Beech
So ion a tight loop, it would be much better to use add range so not as to lose performance due to all the internal newing and pounding the GC - johnc 2008-09-19 07:22
Actually, due to deferred execution, using Concat would likely be faster because it avoids object allocation - Concat doesn't copy anything, it just creates links between the lists so when enumerating and you reach the end of one it transparently takes you to the start of the next - Greg Beech 2008-09-19 07:32


29

The big difference is that AddRange mutates that list against which it is called whereas Concat creates a new List. Hence they have different uses.

Also Concat is an extension method that applies to any IEnumerable and returns an IEnumerable you need a .ToList() to result in a new List.

If you want to extend the content of an existing list use AddRange.

If you are creating a new list from two IEnumerable sources then use Concat with .ToList. This has the quality that it does not mutate either of sources.

If you only ever need to enumerate the contents of two Lists (or any other IEnumerable) then simply use Concat each time, this has the advantage of not actually allocating new memory to hold the unified list.

2008-09-19 07:26
by AnthonyWJones
+1, Indeed, if you forget to 'tolist', concat silently does nothin - smirkingman 2014-05-01 12:07
Ads