c# remove duplicates from list code example

Example 1: remove duplicated from object array c#

import System.Linq;
// for simple array
int[] nums = { 1, 2, 3, 4, 3, 55, 23, 2 };
int[] dist = nums.Distinct().ToArray();

// for object array/list
// example class to remove duplicates based on property
class Order{
	public int i, j;
  	Order(int i, int j){
    	this.i = i;
     	this.j = j;
    }
}

// create this class
class Comparer : IEqualityComparer<Connection> {
    public bool Equals(Order x, Order y) {
        return x.i == y.i; // based on variable i
    }
    public int GetHashCode(Order obj) {
        return obj.i.GetHashCode(); // hashcode of variable to compare
    }
}

// main
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);
// duplicates removed
List<Order> rem_dup = list.Distinct(new Comparer()).ToList();
// List rem_dup has no duplicates based on property i of Order class

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++)
        {
            // Populate numbers with just even numbers.
            evenNumbers.Add(i * 2);

            // Populate oddNumbers with just odd numbers.
            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);

        // Create a new HashSet populated with even numbers.
        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(" }");
    }
}

/* This example produces output similar to the following:
 * evenNumbers contains 5 elements: { 0 2 4 6 8 }
 * oddNumbers contains 5 elements: { 1 3 5 7 9 }
 * numbers UnionWith oddNumbers...
 * numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 }
 */