.NET List<T> Concat 与 AddRange

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/100196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 09:59:36  来源:igfitidea点击:

.NET List<T> Concat vs AddRange

.netlinqlistextension-methods

提问by johnc

What is the difference between the AddRangeand Concatfunctions on a generic List? Is one recommended over the other?

泛型列表上的AddRangeConcat函数之间有什么区别?一个比另一个推荐吗?

回答by Greg Beech

They have totally different semantics.

它们具有完全不同的语义。

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

AddRange 通过向列表添加其他项目来修改列表。

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

Concat 返回一个包含列表和其他项目的新序列,而不修改列表。

Choose whichever one has the semantics you want.

选择具有您想要的语义的任何一个。

回答by AnthonyWJones

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.

最大的区别是 AddRange 改变了它被调用的列表,而 Concat 创建了一个新列表。因此它们有不同的用途。

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.

Concat 也是一个扩展方法,适用于任何 IEnumerable 并返回一个 IEnumerable,您需要一个 .ToList() 来生成一个新列表。

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

如果要扩展现有列表的内容,请使用 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.

如果要从两个 IEnumerable 源创建新列表,请使用带有 .ToList 的 Concat。这具有不会使任何一个来源发生变异的品质。

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.

如果您只需要枚举两个列表(或任何其他 IEnumerable)的内容,那么每次只需使用 Concat,这样做的优点是实际上不会分配新内存来保存统一列表。

回答by Haithem KAROUI

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.

主要思想是 AddRange 在大尺寸集合时要快得多。

Here is the Link

这是链接

Hope this helps,

希望这可以帮助,