Introduction
This snippet shows how to remove duplicate values from a generic List<T>. We can remove duplicates values from list using Enumerable.Distinct() method.
C# Program:
using System;
using System.Linq;
using System.Collections.Generic;
namespace DotNetMirror
{
class RemoveDuplicatesList
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 1, 2, 3, 5, 2, 4, 3, 4 };
List<int> distinctNumbers = numbers.Distinct().ToList(); //Returns distinct elements from a sequence
foreach (int i in distinctNumbers)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
VB.NET Program:
Imports System.Linq
Imports System.Collections.Generic
Namespace DotNetMirror
Class RemoveDuplicatesList
Public Shared Sub Main()
Dim numbers As New List(Of Integer)() From {1, 1, 2, 3, 5, 2, 4, 3, 4}
Dim distinctNumbers As List(Of Integer) = numbers.Distinct().ToList()'Returns distinct elements from a sequence
For Each i As Integer In distinctNumbers
Console.WriteLine(i)
Next
Console.ReadLine()
End Sub
End Class
End Namespace
Output
1
2
3
5
4
Note: If you want to order as well use
numbers.Distinct().OrderBy(x => x).ToList()