Append a value to the end of a List in C#
This post will discuss how to append a value to the end of a list in C#.
1. Using List<T>.Add() Method
The recommended approach to insert an object at the end of a list is using the List<T>.Add() method. The following example demonstrates how to insert an integer in a List<int>.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4 }; int item = 5; nums.Add(item); Console.WriteLine(String.Join(", ", nums)); // 1, 2, 3, 4, 5 } } |
2. Using List<T>.Insert() Method
The List<T>.Insert() method inserts the specified element into the List<T> at the specified index. It can be used as follows to insert an element at the end of a list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4 }; int item = 5; nums.Insert(nums.Count, item); Console.WriteLine(String.Join(", ", nums)); // 1, 2, 3, 4, 5 } } |
3. Using Enumerable.Append() Method
Starting with .NET Framework 4.7.1, you can use the Enumerable.Append() method to append a value to the end of a sequence. This method does not modify the items of the original sequence, but returns a new collection that ends with the specified element. The following code example demonstrates how to use Append() method to create a copy of a list with the new element.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4 }; int item = 5; List<int> newNums = nums.Append(item).ToList(); Console.WriteLine(String.Join(", ", newNums)); // 1, 2, 3, 4, 5 } } |
That’s all about appending a value to the end of a list in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)