How to Remove Duplicates from a C# List

Leave a comment

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:

 

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#

Leave a Reply

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