Adding Items To The End Of A Collection in C# & .NET
[C#, .NET]
In our previous post, “Adding Items To The Beginning Of A Collection in C# & .NET”, we looked at several ways to add items to the beginning of a collection, in this case a List.
There were three techniques:
- Insert method
- Prepend method
- Collection initializers
In this post, we will look at the opposite problem: how to add items to the end of a collection.
Likewise, there are also three techniques.
Insert
We can also use the Insert method here; the twist is that we need to specify where exactly to insert - the tail of the collection.
We obtain this by retrieving the number of items already in the list.
Like so:
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
numbers.Insert(numbers.Count, 100);
Append
Another way is to use the Append method.
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var newList = numbers.Append(100);
This returns a new List with the required element appended to the end.
Collection Expressions
As in the previous case, we can also use collection expressions to compose our new List.
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
List<int> newList = [.. numbers, 100];
TLDR
There are at least three ways to append elements to an existing List.
Happy hacking!