Maurdekye Maurdekye - 20 days ago 6
C# Question

In C#, is there a default way to create a new list with an item added, without modifying the original list?

Basicially an appending function, where if I give one list and an item, it returns a totally new list with that item added. I'm not asking how to do it, I want to know if there's already an efficient way to do so built into the .Net source. Obviously I could just do something like this;

List<string> newList = new List<string>();
newList.AddRange(oldList);
newList.Add(newElem);


But is there a better way?

Answer

Try this:

List<string> newList = new List<string>(oldList) { newElem };