ZetCode

C# List

last modified November 15, 2026

This article is a guide to the generic List<T> collection in C#. We create lists, add, insert, find, and remove elements, sort and convert lists, and look at how a list manages its memory.

C# List

List<T> from the System.Collections.Generic namespace is a strongly typed, resizable collection of elements that can be accessed by a zero-based index. Internally, it stores its elements in an array. When the array is full, the list allocates a larger one and copies the elements over; this is why adding to the end of a list is fast on average.

Because the elements live in one contiguous array, a list has these properties:

The following table lists commonly used members of the class.

Member Description
Count The number of elements in the list.
Capacity The size of the internal array.
Add, AddRange Add elements to the end of the list.
Insert, InsertRange Insert elements at the given index.
Remove, RemoveAt, RemoveAll, RemoveRange, Clear Remove elements.
Contains, IndexOf, LastIndexOf, Exists Check for elements and get their positions.
Find, FindAll, FindIndex, FindLast, FindLastIndex, TrueForAll Search with a predicate.
Sort, Reverse, BinarySearch Reorder the list in place and search a sorted list.
ConvertAll, ToArray, GetRange, AsReadOnly Create new lists, arrays, and read-only views.

C# List creation

A list can be created with an object initializer or with a collection expression.

Program.cs
var words = new List<string> { "forest", "oak", "river", "falcon" };
Console.WriteLine(string.Join(", ", words));

List<string> words2 = ["sky", "cloud", "rain"];
Console.WriteLine(string.Join(", ", words2));

List<int> empty = [];
Console.WriteLine(empty.Count);

We create three lists of different kinds.

var words = new List<string> { "forest", "oak", "river", "falcon" };

The collection initializer creates a list and calls Add for each of the values inside the curly brackets. Between the angle brackets, we specify the type of the elements.

List<string> words2 = ["sky", "cloud", "rain"];

A collection expression (C# 12) is a terser syntax. The elements are placed inside square brackets and the target type is taken from the declaration.

List<int> empty = [];

An empty pair of brackets creates an empty list.

Console.WriteLine(string.Join(", ", words));

To get a quick look at a list, we join its elements into a string with string.Join. More options are described in the List to string article.

$ dotnet run
forest, oak, river, falcon
sky, cloud, rain
0

C# List access elements

Elements are accessed with the indexer []. The index is zero-based.

Program.cs
List<int> vals = [0, 1, 2, 3, 4, 5];

Console.WriteLine(vals[0]);
Console.WriteLine(vals[1]);

Console.WriteLine(vals[vals.Count - 1]);
Console.WriteLine(vals[^1]);
Console.WriteLine(vals[^2]);

vals[0] = 10;
Console.WriteLine(string.Join(", ", vals));

try
{
    Console.WriteLine(vals[6]);
}
catch (ArgumentOutOfRangeException e)
{
    Console.WriteLine(e.Message);
}

We read elements from the start and from the end of the list and modify the first one.

Console.WriteLine(vals[vals.Count - 1]);
Console.WriteLine(vals[^1]);
Console.WriteLine(vals[^2]);

The last element has the index Count - 1. The hat operator ^ counts from the end: ^1 is the last element and ^2 the one before it.

vals[0] = 10;

The indexer is also used to replace an element.

Console.WriteLine(vals[6]);

An index outside the range 0..Count-1 throws an ArgumentOutOfRangeException. Note that the capacity of the list does not matter; only the elements counted by Count are accessible.

$ dotnet run
0
1
5
5
4
10, 1, 2, 3, 4, 5
Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')

C# List ranges and GetRange

Since .NET 8, List<T> has a Slice method, so it supports the range operator ... The GetRange method does the same with a start index and a count.

Program.cs
List<int> vals = [0, 1, 2, 3, 4, 5, 6, 7];

List<int> part = vals[2..5];
Console.WriteLine(string.Join(", ", part));

List<int> part2 = vals.GetRange(5, 3);
Console.WriteLine(string.Join(", ", part2));

part[0] = 100;
Console.WriteLine(string.Join(", ", vals));

We take two parts of a list of integers.

List<int> part = vals[2..5];

The range 2..5 includes the element at index 2 and excludes the element at index 5. The compiler translates it to a Slice(2, 3) call.

List<int> part2 = vals.GetRange(5, 3);

GetRange takes the starting index and the number of elements.

part[0] = 100;
Console.WriteLine(string.Join(", ", vals));

Both methods return a new list that holds a shallow copy of the elements. Changing the new list does not affect the original one. (This is different from a Span, which is a view into existing memory.)

$ dotnet run
2, 3, 4
5, 6, 7
0, 1, 2, 3, 4, 5, 6, 7

C# List add and insert elements

Add appends an element and AddRange appends the elements of a collection. Insert and InsertRange put elements at the given index; the elements after it are shifted to the right.

Program.cs
List<string> words = ["forest", "oak", "river", "falcon"];

words.Add("sky");
words.Add("ocean");

string[] words2 = ["owl", "hawk"];
words.AddRange(words2);

Console.WriteLine(string.Join(", ", words));

words.Insert(0, "cloud");
words.Insert(words.Count, "rain");
words.InsertRange(2, ["water", "wave"]);

Console.WriteLine(string.Join(", ", words));

We add and insert words into a list.

string[] words2 = ["owl", "hawk"];
words.AddRange(words2);

AddRange accepts any IEnumerable<T>, here an array.

words.Insert(0, "cloud");
words.Insert(words.Count, "rain");
words.InsertRange(2, ["water", "wave"]);

Inserting at index 0 puts the element at the start of the list. The index Count is also valid; inserting there is the same as Add. InsertRange puts the collection at index 2. The article List Add & Insert covers these methods in more detail.

$ dotnet run
forest, oak, river, falcon, sky, ocean, owl, hawk
cloud, forest, water, wave, oak, river, falcon, sky, ocean, owl, hawk, rain

C# List Contains, IndexOf, and Exists

Contains checks if an element is in the list, IndexOf and LastIndexOf return its position, and Exists checks if any element matches a predicate.

Program.cs
List<string> words = ["forest", "oak", "river", "falcon", "oak"];

Console.WriteLine(words.Contains("oak"));
Console.WriteLine(words.Contains("Oak"));

Console.WriteLine(words.IndexOf("oak"));
Console.WriteLine(words.LastIndexOf("oak"));
Console.WriteLine(words.IndexOf("sky"));

Console.WriteLine(words.Exists(w => w.StartsWith('f')));
Console.WriteLine(words.Exists(w => w.Length > 6));

We check for words in a list.

Console.WriteLine(words.Contains("oak"));
Console.WriteLine(words.Contains("Oak"));

Contains uses the default equality comparer of the type; for strings, the comparison is ordinal and case-sensitive, so "Oak" is not found.

Console.WriteLine(words.IndexOf("oak"));
Console.WriteLine(words.LastIndexOf("oak"));
Console.WriteLine(words.IndexOf("sky"));

The word "oak" is at the indexes 1 and 4. For a missing element, IndexOf returns -1.

Console.WriteLine(words.Exists(w => w.StartsWith('f')));

Exists takes a predicate. Here we check if some word starts with "f". See also the List Contains & Exists article.

$ dotnet run
True
False
1
4
-1
True
False

C# List remove elements

The Remove, RemoveAt, RemoveAll, RemoveRange, and Clear methods remove elements from a list.

Program.cs
List<int> nums = [0, 1, 2, -3, 4, -5, 6, 7, -8, 9, 10];

int removed = nums.RemoveAll(e => e < 0);
Console.WriteLine($"{removed} removed: {string.Join(", ", nums)}");

bool ok = nums.Remove(0);
Console.WriteLine($"{ok}: {string.Join(", ", nums)}");

Console.WriteLine(nums.Remove(42));

nums.RemoveAt(nums.Count - 1);
Console.WriteLine(string.Join(", ", nums));

nums.RemoveRange(0, 3);
Console.WriteLine(string.Join(", ", nums));

nums.Clear();
Console.WriteLine(nums.Count);

We remove elements from a list of integers.

int removed = nums.RemoveAll(e => e < 0);

RemoveAll removes all elements that satisfy the predicate, in our case the negative values. It returns the number of removed elements.

bool ok = nums.Remove(0);

Remove removes the first occurrence of the value. It returns false when the value is not in the list; no exception is thrown.

nums.RemoveAt(nums.Count - 1);

RemoveAt removes the element at the given index, here the last one.

nums.RemoveRange(0, 3);

RemoveRange takes the starting index and the number of elements to remove. Clear then removes all remaining elements. The List Remove article has more examples.

$ dotnet run
3 removed: 0, 1, 2, 4, 6, 7, 9, 10
True: 1, 2, 4, 6, 7, 9, 10
False
1, 2, 4, 6, 7, 9
6, 7, 9
0

C# loop over List

A list can be traversed with foreach, with a for loop, or with the ForEach method.

Program.cs
List<string> words = ["forest", "oak", "river", "falcon"];

foreach (var word in words)
{
    Console.WriteLine(word);
}

for (int i = 0; i < words.Count; i++)
{
    Console.WriteLine($"{i}: {words[i]}");
}

words.ForEach(word => Console.WriteLine(word.ToUpper()));

foreach (var (i, word) in words.Index())
{
    Console.WriteLine($"{i} -> {word}");
}

We print the words of a list in four ways.

for (int i = 0; i < words.Count; i++)
{
    Console.WriteLine($"{i}: {words[i]}");
}

The classic for loop gives us the index of each element.

words.ForEach(word => Console.WriteLine(word.ToUpper()));

The ForEach method calls an Action<T> for each element.

foreach (var (i, word) in words.Index())
{
    Console.WriteLine($"{i} -> {word}");
}

The LINQ Index method (.NET 9) pairs each element with its index, so we can get the index in a foreach loop as well.

$ dotnet run
forest
oak
river
falcon
0: forest
1: oak
2: river
3: falcon
FOREST
OAK
RIVER
FALCON
0 -> forest
1 -> oak
2 -> river
3 -> falcon

C# List modified during enumeration

A list must not be changed while it is enumerated with foreach. The enumerator checks an internal version number and throws an InvalidOperationException when the list was modified.

Program.cs
List<int> nums = [1, -2, 3, -4, 5];

try
{
    foreach (var e in nums)
    {
        if (e < 0)
        {
            nums.Remove(e);
        }
    }
}
catch (InvalidOperationException ex)
{
    Console.WriteLine(ex.Message);
}

Console.WriteLine(string.Join(", ", nums));

for (int i = nums.Count - 1; i >= 0; i--)
{
    if (nums[i] < 0)
    {
        nums.RemoveAt(i);
    }
}

Console.WriteLine(string.Join(", ", nums));

We try to remove the negative values in a foreach loop.

foreach (var e in nums)
{
    if (e < 0)
    {
        nums.Remove(e);
    }
}

The removal of -2 succeeds; the exception is thrown when the loop asks for the next element. The list is left half processed: -4 is still there.

for (int i = nums.Count - 1; i >= 0; i--)
{
    if (nums[i] < 0)
    {
        nums.RemoveAt(i);
    }
}

A for loop that goes backwards can remove elements safely, because a removal shifts only the elements that were already visited. Simpler still is nums.RemoveAll(e => e < 0).

$ dotnet run
Collection was modified; enumeration operation may not execute.
1, 3, -4, 5
1, 3, 5

C# List sort and reverse

Sort sorts the list in place and Reverse reverses the order of its elements.

Program.cs
List<int> nums = [2, 1, 5, 4, 3];

nums.Reverse();
Console.WriteLine(string.Join(", ", nums));

nums.Sort();
Console.WriteLine(string.Join(", ", nums));

List<string> words = ["falcon", "Owl", "sky", "hawk", "stork", "eagle"];

words.Sort((a, b) => a.Length.CompareTo(b.Length));
Console.WriteLine(string.Join(", ", words));

words.Sort(StringComparer.OrdinalIgnoreCase);
Console.WriteLine(string.Join(", ", words));

words.Sort((a, b) => b.CompareTo(a));
Console.WriteLine(string.Join(", ", words));

We sort lists of integers and strings.

nums.Reverse();

On a List<T> variable, Reverse binds to the instance method, which reverses the list in place. (On an array, the same call binds to the LINQ method, which returns a new sequence.)

words.Sort((a, b) => a.Length.CompareTo(b.Length));

Without arguments, Sort uses the default comparer. A Comparison<T> delegate defines a custom order; here we sort the words by their length.

words.Sort(StringComparer.OrdinalIgnoreCase);

An IComparer<T> object can be passed as well. Here we sort the words case-insensitively.

words.Sort((a, b) => b.CompareTo(a));

Swapping the arguments gives descending order. Note that Sort is not stable: elements that compare equal may change their relative order. The LINQ OrderBy method is stable. The sort List article covers sorting in depth.

$ dotnet run
3, 4, 5, 1, 2
1, 2, 3, 4, 5
Owl, sky, hawk, stork, eagle, falcon
eagle, falcon, hawk, Owl, sky, stork
stork, sky, Owl, hawk, falcon, eagle

C# List Find methods

FindAll returns a new list with all elements that match a predicate. Find and FindLast return the first and the last matching element, FindIndex and FindLastIndex their indexes. TrueForAll checks if all elements match.

Program.cs
List<int> nums = [6, -2, 1, 5, 4, 3, 2, 9, -1, 7];

List<int> positive = nums.FindAll(e => e > 0);
Console.WriteLine(string.Join(", ", positive));

Console.WriteLine(nums.Find(e => e < 0));
Console.WriteLine(nums.FindIndex(e => e < 0));
Console.WriteLine(nums.FindLast(e => e < 0));
Console.WriteLine(nums.FindLastIndex(e => e < 0));

Console.WriteLine(nums.Find(e => e > 100));
Console.WriteLine(nums.FindIndex(e => e > 100));

Console.WriteLine(nums.TrueForAll(e => e % 2 == 0));
Console.WriteLine(nums.TrueForAll(e => e > -10));

We search a list of integers for negative values.

Console.WriteLine(nums.Find(e => e > 100));
Console.WriteLine(nums.FindIndex(e => e > 100));

When no element matches, Find returns the default value of the type, which is 0 for int and null for reference types. FindIndex returns -1. With value types, the default is ambiguous: 0 may also be a real element, so use FindIndex or Exists when it matters.

Console.WriteLine(nums.TrueForAll(e => e % 2 == 0));

Not all values are even, so TrueForAll returns false. See also the List Find article.

$ dotnet run
6, 1, 5, 4, 3, 2, 9, 7
-2
1
-1
8
0
-1
False
True

C# List ConvertAll

ConvertAll applies a Converter<TInput, TOutput> to each element and returns a new list of the results. The result type may differ from the type of the source.

Program.cs
List<string> words = ["falcon", "owl", "sky", "hawk", "stork"];

List<string> upper = words.ConvertAll(s => s.ToUpper());
List<int> lengths = words.ConvertAll(s => s.Length);

Console.WriteLine(string.Join(", ", upper));
Console.WriteLine(string.Join(", ", lengths));

List<string> numbers = ["1", "4", "9", "16"];
List<int> ints = numbers.ConvertAll(int.Parse);
List<double> roots = ints.ConvertAll(x => Math.Sqrt(x));

Console.WriteLine(string.Join(", ", roots));

We convert lists of words and numbers.

List<int> lengths = words.ConvertAll(s => s.Length);

The new list contains the lengths of the words.

List<int> ints = numbers.ConvertAll(int.Parse);

A method group can be passed instead of a lambda; here int.Parse turns strings into integers. The List ConvertAll article shows more conversions.

$ dotnet run
FALCON, OWL, SKY, HAWK, STORK
6, 3, 3, 4, 5
1, 2, 3, 4

C# List copies and views

A list is a reference type. Assigning it to another variable copies the reference, not the elements.

Program.cs
List<int> nums = [1, 2, 3, 4];

int[] arr = nums.ToArray();
Console.WriteLine(arr.GetType());

arr[0] = 100;
Console.WriteLine(string.Join(", ", nums));

var copy = new List<int>(nums);
copy.Add(5);
Console.WriteLine(string.Join(", ", nums));
Console.WriteLine(string.Join(", ", copy));

var alias = nums;
alias.Add(5);
Console.WriteLine(string.Join(", ", nums));

IReadOnlyList<int> view = nums.AsReadOnly();
nums.Add(6);
Console.WriteLine(view.Count);
Console.WriteLine(view.GetType());

We compare an array copy, a new list, a second reference, and a read-only view.

int[] arr = nums.ToArray();

ToArray copies the elements into a new array. Changing the array does not change the list.

var copy = new List<int>(nums);

The constructor that takes a collection creates an independent list.

var alias = nums;
alias.Add(5);

Both variables refer to the same list, so the added element appears in nums.

IReadOnlyList<int> view = nums.AsReadOnly();
nums.Add(6);
Console.WriteLine(view.Count);

AsReadOnly returns a ReadOnlyCollection<T> wrapper. It has no methods that modify the list, but it is not a copy: it sees the element added afterwards. The article Copy by value vs copy by reference explains the difference in detail.

$ dotnet run
System.Int32[]
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4, 5
1, 2, 3, 4, 5
6
System.Collections.ObjectModel.ReadOnlyCollection`1[System.Int32]

C# List capacity

Capacity is the length of the internal array, Count the number of elements actually stored. When an element is added to a full list, the capacity doubles.

Program.cs
var vals = new List<int>();
int last = -1;

for (int i = 0; i < 40; i++)
{
    if (vals.Capacity != last)
    {
        Console.WriteLine($"Count: {vals.Count,2}, Capacity: {vals.Capacity}");
        last = vals.Capacity;
    }

    vals.Add(i);
}

vals.RemoveRange(5, 35);
Console.WriteLine($"Count: {vals.Count}, Capacity: {vals.Capacity}");

vals.TrimExcess();
Console.WriteLine($"Count: {vals.Count}, Capacity: {vals.Capacity}");

var big = new List<int>(1000);
Console.WriteLine($"Count: {big.Count}, Capacity: {big.Capacity}");

big.EnsureCapacity(1500);
Console.WriteLine($"Count: {big.Count}, Capacity: {big.Capacity}");

We add forty elements and print the capacity each time it changes.

var vals = new List<int>();

A new empty list has capacity 0; it allocates no array. The first Add allocates an array of four elements, and each time the array is full, a new one of double size is allocated and the elements are copied.

vals.RemoveRange(5, 35);

Removing elements does not shrink the internal array; the capacity stays 64.

vals.TrimExcess();

TrimExcess sets the capacity to the number of elements, but only if the list uses less than 90% of its capacity. It is useful for a large list that is no longer going to grow.

var big = new List<int>(1000);

When we know the approximate number of elements in advance, we pass it to the constructor and avoid the repeated reallocations.

big.EnsureCapacity(1500);

EnsureCapacity makes the capacity at least the given number. It grows the array the same way Add does, so the new capacity is 2000, double the old one, not 1500.

$ dotnet run
Count:  0, Capacity: 0
Count:  1, Capacity: 4
Count:  5, Capacity: 8
Count:  9, Capacity: 16
Count: 17, Capacity: 32
Count: 33, Capacity: 64
Count: 5, Capacity: 64
Count: 5, Capacity: 5
Count: 0, Capacity: 1000
Count: 0, Capacity: 2000

C# List BinarySearch

BinarySearch searches a sorted list in O(log n) time. It returns the index of the element if found. Otherwise, it returns a negative number, the bitwise complement of the index where the element would be inserted.

Program.cs
List<int> nums = [1, 3, 5, 7, 9];

Console.WriteLine(nums.BinarySearch(5));

int idx = nums.BinarySearch(6);
Console.WriteLine(idx);
Console.WriteLine(~idx);

if (idx < 0)
{
    nums.Insert(~idx, 6);
}

Console.WriteLine(string.Join(", ", nums));

We search a sorted list and use the result to insert a missing value at the right position.

int idx = nums.BinarySearch(6);
Console.WriteLine(idx);
Console.WriteLine(~idx);

The value 6 is not in the list, so the method returns -4. Its complement ~idx is 3, the index of the first element larger than 6.

if (idx < 0)
{
    nums.Insert(~idx, 6);
}

Inserting at that index keeps the list sorted. The result of BinarySearch on an unsorted list is undefined.

$ dotnet run
2
-4
3
1, 3, 5, 6, 7, 9

C# List shuffle

Random.Shuffle (.NET 8) shuffles a span or an array in place. A list is not an array, but CollectionsMarshal.AsSpan gives us a span over its internal array.

Program.cs
using System.Runtime.InteropServices;

List<int> vals = [1, 2, 3, 4, 5, 6, 7, 8];

Random.Shared.Shuffle(CollectionsMarshal.AsSpan(vals));
Console.WriteLine(string.Join(" ", vals));

var rng = new Random(42);
List<string> words = ["falcon", "owl", "sky", "hawk", "stork"];

rng.Shuffle(CollectionsMarshal.AsSpan(words));
Console.WriteLine(string.Join(" ", words));

We shuffle two lists.

Random.Shared.Shuffle(CollectionsMarshal.AsSpan(vals));

Random.Shared is a thread-safe instance that is seeded randomly, so each run gives a different order. The span must not be used after the list is resized, because it would point to the old array.

var rng = new Random(42);

A Random created with a seed produces the same sequence each time, which is handy for tests. The second line of the output is the same on every run. The Random article has more on random numbers.

$ dotnet run
2 1 3 5 8 7 6 4
hawk owl sky stork falcon

C# List and LINQ

Language-Integrated Query (LINQ) adds many extension methods to all collections, lists included. Unlike the methods of List<T>, they never modify the source; they return new sequences or single values.

Program.cs
List<int> vals = [-1, 2, 1, -3, 7, -9, 5, 9, -4, 8];

Console.WriteLine($"Count: {vals.Count}");
Console.WriteLine($"Even values: {vals.Count(e => e % 2 == 0)}");
Console.WriteLine($"Sum: {vals.Sum()}");
Console.WriteLine($"Sum of positive values: {vals.Where(e => e > 0).Sum()}");
Console.WriteLine($"Average: {vals.Average()}");
Console.WriteLine($"Max: {vals.Max()}");
Console.WriteLine($"Min: {vals.Min()}");

We compute aggregate values of a list of integers.

Console.WriteLine($"Count: {vals.Count}");
Console.WriteLine($"Even values: {vals.Count(e => e % 2 == 0)}");

vals.Count is the property of the list, while vals.Count(predicate) is the LINQ method that counts the matching elements. See the List Count article.

Console.WriteLine($"Sum of positive values: {vals.Where(e => e > 0).Sum()}");

We filter the positive values with Where and sum them.

$ dotnet run
Count: 10
Even values: 3
Sum: 15
Sum of positive values: 32
Average: 1.5
Max: 9
Min: -9

C# List ordering with LINQ

The OrderBy, ThenBy, and their descending variants sort by one or more keys. They return a new sequence; the original list is not changed.

Program.cs
List<User> users =
[
    new("John", "Doe", 1230),
    new("Lucy", "Novak", 670),
    new("Ben", "Walter", 2050),
    new("Robin", "Brown", 2300),
    new("Amy", "Doe", 1250),
    new("Joe", "Draker", 1190),
    new("Janet", "Doe", 980),
    new("Albert", "Novak", 1930),
];

Console.WriteLine("ascending by last name and salary");

var sorted = users.OrderBy(u => u.LastName).ThenBy(u => u.Salary);

foreach (var user in sorted)
{
    Console.WriteLine(user);
}

Console.WriteLine("descending by last name and salary");

var sorted2 = users.OrderByDescending(u => u.LastName)
    .ThenByDescending(u => u.Salary);

foreach (var user in sorted2)
{
    Console.WriteLine(user);
}

Console.WriteLine($"original first: {users[0]}");

record User(string FirstName, string LastName, int Salary);

We sort users by their last names and then by their salaries.

var sorted = users.OrderBy(u => u.LastName).ThenBy(u => u.Salary);

The users are sorted by their last names in ascending order. Users with the same last name are sorted by their salaries.

var sorted2 = users.OrderByDescending(u => u.LastName)
    .ThenByDescending(u => u.Salary);

Here both keys are sorted in descending order.

Console.WriteLine($"original first: {users[0]}");

The list itself keeps its original order. More in the LINQ Order article.

$ dotnet run
ascending by last name and salary
User { FirstName = Robin, LastName = Brown, Salary = 2300 }
User { FirstName = Janet, LastName = Doe, Salary = 980 }
User { FirstName = John, LastName = Doe, Salary = 1230 }
User { FirstName = Amy, LastName = Doe, Salary = 1250 }
User { FirstName = Joe, LastName = Draker, Salary = 1190 }
User { FirstName = Lucy, LastName = Novak, Salary = 670 }
User { FirstName = Albert, LastName = Novak, Salary = 1930 }
User { FirstName = Ben, LastName = Walter, Salary = 2050 }
descending by last name and salary
User { FirstName = Ben, LastName = Walter, Salary = 2050 }
User { FirstName = Albert, LastName = Novak, Salary = 1930 }
User { FirstName = Lucy, LastName = Novak, Salary = 670 }
User { FirstName = Joe, LastName = Draker, Salary = 1190 }
User { FirstName = Amy, LastName = Doe, Salary = 1250 }
User { FirstName = John, LastName = Doe, Salary = 1230 }
User { FirstName = Janet, LastName = Doe, Salary = 980 }
User { FirstName = Robin, LastName = Brown, Salary = 2300 }
original first: User { FirstName = John, LastName = Doe, Salary = 1230 }

C# List remove duplicates

The LINQ Distinct method returns the unique elements of a sequence. It keeps the first occurrence of each value, in the original order.

Program.cs
List<int> nums = [1, 2, 2, 3, 4, 4, 5, 1];

List<int> unique = nums.Distinct().ToList();
Console.WriteLine(string.Join(", ", unique));

List<string> words = ["sky", "Sky", "SKY", "owl", "Owl"];

var unique2 = words.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
Console.WriteLine(string.Join(", ", unique2));

var set = new HashSet<int>(nums);
Console.WriteLine(string.Join(", ", set));

We remove duplicates from lists of integers and words.

var unique2 = words.Distinct(StringComparer.OrdinalIgnoreCase).ToList();

An equality comparer changes what counts as a duplicate. With a case-insensitive comparer, "sky", "Sky", and "SKY" are one value, and the first one is kept.

var set = new HashSet<int>(nums);

A HashSet<T> also drops the duplicates. Its enumeration order is not guaranteed, although for a small set of integers it usually follows the insertion order.

$ dotnet run
1, 2, 3, 4, 5
sky, owl
1, 2, 3, 4, 5

Source

List<T> class - .NET API

Collections and data structures - .NET

In this article we have worked with the C# List<T> collection. See also the array, collection, LinkedList, and LINQ tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.