c# remove duplicates from list code example
Example 1: remove duplicated from object array c#
import System.Linq;
int[] nums = { 1, 2, 3, 4, 3, 55, 23, 2 };
int[] dist = nums.Distinct().ToArray();
class Order{
public int i, j;
Order(int i, int j){
this.i = i;
this.j = j;
}
}
class Comparer : IEqualityComparer<Connection> {
public bool Equals(Order x, Order y) {
return x.i == y.i;
}
public int GetHashCode(Order obj) {
return obj.i.GetHashCode();
}
}
List<Order> list = new List<Order>();
list.Add(1, 2);
list.Add(2, 3);
list.Add(1, 4);
list.Add(4, 5);
list.Add(1, 6);
List<Order> rem_dup = list.Distinct(new Comparer()).ToList();
Example 2: c# list remove item based on property duplicate
fooArray.GroupBy(x => x.Id).Select(x => x.First());
Example 3: Remove duplicates from a List in C#
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> evenNumbers = new HashSet<int>();
HashSet<int> oddNumbers = new HashSet<int>();
for (int i = 0; i < 5; i++)
{
evenNumbers.Add(i * 2);
oddNumbers.Add((i * 2) + 1);
}
Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);
DisplaySet(evenNumbers);
Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count);
DisplaySet(oddNumbers);
HashSet<int> numbers = new HashSet<int>(evenNumbers);
Console.WriteLine("numbers UnionWith oddNumbers...");
numbers.UnionWith(oddNumbers);
Console.Write("numbers contains {0} elements: ", numbers.Count);
DisplaySet(numbers);
}
private static void DisplaySet(HashSet<int> set)
{
Console.Write("{");
foreach (int i in set)
{
Console.Write(" {0}", i);
}
Console.WriteLine(" }");
}
}