Remove Duplicate Items from an Array or Collection - CSharp LINQ

CSharp examples for LINQ:IEnumerable

Description

Remove Duplicate Items from an Array or Collection

Demo Code

using System;/*from  w w w. ja  v  a2  s.  com*/
using System.Collections.Generic;
using System.Linq;
using System.Text;
class MainClass
{
   static void Main(string[] args)
   {
      // create a list of fruit, including duplicates
      List<Item> myList = new List<Item>() {
         new Item("apple", "green"),
         new Item("apple", "red"),
         new Item("orange", "orange"),
         new Item("orange", "orange"),
         new Item("file", "yellow"),
         new Item("mango", "yellow"),
         new Item("cherry", "red"),
         new Item("fig", "brown"),
         new Item("fig", "brown"),
         new Item("fig", "brown"),
         new Item("new", "red"),
         new Item("pear", "green")
      };
      // use the Distinct method to remove duplicates
      // and print out the unique entries that remain
      foreach (Item fruit in myList.Distinct(new ItemComparer()))
      {
         Console.WriteLine("Item: {0}:{1}", fruit.Name, fruit.Color);
      }
   }
}
class ItemComparer : IEqualityComparer<Item>
{
   public bool Equals(Item first, Item second)
   {
      return first.Name == second.Name && first.Color == second.Color;
   }
   public int GetHashCode(Item fruit)
   {
      return fruit.Name.GetHashCode() + fruit.Name.GetHashCode();
   }
}
class Item
{
   public Item(string nameVal, string colorVal)
   {
      Name = nameVal;
      Color = colorVal;
   }
   public string Name { get; set; }
   public string Color { get; set; }

}

Result


Related Tutorials