To Remove Duplicates From List can be done by many different ways. You can use Distinct extension method to remove duplicates.
Below program that removes duplicates from the list in C#.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// List having duplicate integer elements.
List<int> list = new List<int>();
list.Add(7);
list.Add(2);
list.Add(5);
list.Add(5);
list.Add(2);
list.Add(3);
list.Add(7);
// Get distinct elements and convert again into a list.
List<int> distinct = list.Distinct().ToList();
foreach (int value in distinct)
{
Console.WriteLine("Distinct : {0}", value);
}
}
}
OR
You can use LINQ to object to remove duplicates from list,
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// List having duplicate string elements.
List<string> list = new List<string>();
list.Add("A");
list.Add("A");
list.Add("C");
list.Add("D");
list.Add("B");
list.Add("A");
list.Add("E");
list.Add("E");
// Get distinct elements.
var distinct = (from item in list orderby item select item).Distinct();
foreach (string value in distinct)
{
Console.WriteLine("Distinct : {0}", value);
}
}
}