Difference between a List's Add and Append method?

后端 未结 2 1211
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-31 01:17

Is there a difference between the .Append() and the .Add() method for lists in C#? I tried searching in Google and in the site but to my surprise n

2条回答
  •  别那么骄傲
    2020-12-31 01:26

    List in C# only has the void Add(T item) method to modify the instance add a single item to the list.

    IEnumerable Append(this IEnumerable source, T element) on the other hand is an extension method defined on the IEnumerable interface (which is implemented by all lists). It does not modify the original list instance, but returns a new enumerable which will yield the specified element at the end of the sequence.

    They cannot be used interchangably and behave differently with different outcomes and different side effects. Asking about their relative performance does not make sense as such.

    var list = new List();
    list.Add("one");
    list.Add("two");
    // list contains: [ one, two ]
    
    list.Append("three");
    // list still contains: [ one, two ]
    

提交回复
热议问题