.NET List<T> Concat vs AddRange

.NetLinqListExtension Methods

.Net Problem Overview


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

.Net Solutions


Solution 1 - .Net

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.

Solution 2 - .Net

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<T> and returns an IEnumerable<T> 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<T> 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.

Solution 3 - .Net

I found this interesting article talking about the difference between these 2 structures and comparing their performance...

The main idea is that AddRange is way much faster when its about big size collections.

Here is the Link

Hope this helps,

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjohncView Question on Stackoverflow
Solution 1 - .NetGreg BeechView Answer on Stackoverflow
Solution 2 - .NetAnthonyWJonesView Answer on Stackoverflow
Solution 3 - .NetHaithem KAROUIView Answer on Stackoverflow