.NET List<T> Concat vs AddRange

佐手、 提交于 2019-11-26 08:15:03

问题


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


回答1:


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.




回答2:


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.




回答3:


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,



来源:https://stackoverflow.com/questions/100196/net-listt-concat-vs-addrange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!