Difference between a List's Add and Append method?

后端 未结 2 1226
佛祖请我去吃肉
佛祖请我去吃肉 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<T> in C# only has the void Add(T item) method to modify the instance add a single item to the list.

    IEnumerable<T> Append(this IEnumerable<T> source, T element) on the other hand is an extension method defined on the IEnumerable<T> 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<string>();
    list.Add("one");
    list.Add("two");
    // list contains: [ one, two ]
    
    list.Append("three");
    // list still contains: [ one, two ]
    
    0 讨论(0)
  • 2020-12-31 01:38

    Add is a void.

    Append returns an IEnumerable so you can

    var x = new List<int>();
    x.Add(1);
    x = x.Append(2).Append(3).ToList();
    
    0 讨论(0)
提交回复
热议问题