Insert elements at the end of a list in C#
This post will discuss how to insert elements at the end of a list in C#.
1. Using List<T>.Add() method
The standard solution to add a value to the end of the list is using the List<T>.Add() method. The following example demonstrates how to add a value in a List<T>.
|
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 x = 5; nums.Add(x); Console.WriteLine(String.Join(", ", nums)); // 1, 2, 3, 4, 5 } } |
2. Using Enumerable.Append() method
Alternatively, you can use the Enumerable.Append() method to add a value at the end of a sequence. This returns a copy of the sequence with the new item, and leaves the original sequence untouched. It is available with .NET >= 4.7.1, and can be invoked as below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4 }; int x = 5; nums = nums.Append(x).ToList(); Console.WriteLine(String.Join(", ", nums)); // 1, 2, 3, 4, 5 } } |
3. Using LinkedList<T>.AddLast() method
To adds a new value at the end of the LinkedList<T>, consider using the AddLast() method. The linked list implementation provides a more complete and consistent set of LIFO and FIFO operations. Here’s an example of its usage:
|
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() { LinkedList<int> nums = new LinkedList<int>(); nums.AddLast(1); nums.AddLast(2); nums.AddLast(3); Console.WriteLine(String.Join(", ", nums)); // 1, 2, 3 } } |
That’s all about inserting elements at 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 :)