Remove Duplicates From List in C#

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);
        }
    }
}

2 comments:

  1. Hey there! Someone in my Myspace group shared this website with us so I came to check it out.I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers!Terrific blog and fantastic design and style.

    Bubble
    www.gofastek.com

    ReplyDelete
  2. Mistake does not only teach you how to be strong but also how to stand up again and to do good next time. Visit my site for more information. Have a good day always and thank you for sharing your knowledge and wonderful article to the public. I do hope that you can inspire more readers.

    n8fan.net

    www.n8fan.net

    ReplyDelete