How to Remove Duplicates from a C# List

4 Comments

To remove duplicates from a C# list using Linq, do the following.

  1. Define a new list. Ours has 7 elements, with “2” and “4” repeating
  2. Use Distinct().ToList() to make a new list with the distinct elements
  3. Print out to the console
using System;
using System.Collections.Generic;
using System.Linq;

namespace Carl.RemoveDuplicatesList
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create list with non-unique values
            List<string> l = new List<string>();
            l.Add("1");
            l.Add("2");
            l.Add("2"); // duplicate
            l.Add("3");
            l.Add("4");
            l.Add("4"); // duplicate
            l.Add("5");

            // Make new unique list
            List<string> uniqueList = l.Distinct().ToList();

            // Write to console
            uniqueList.ForEach(i => Console.WriteLine($"{i}"));

            Console.ReadLine();
        }
    }
}

This outputs:

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

See more articles on: C#

4 Responses to How to Remove Duplicates from a C# List

  1. Thank you for the very clear example of how to obtain a unique list. But what if you have a generic collection list? I have that and I am trying to obtain a unique list based on one field in that collection.

  2. Write a function which takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once.

  3. Hallo
    Please i Need help
    I have a Array with 7 element , but i would like to calculate the Addition of element that he comes one time

    Example : int [] Array { 10, 15, 15, 10,5,15,3}

    Addition ist : 5 + 3 = 8

    10 comes two time : Array[0] and Array[3]

    the same with 15

    only 5 and 3 appears one time
    please how i can write the code?

Leave a Reply

Your email address will not be published. Required fields are marked *