Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
linked list

How to remove duplicates from a linked list in C#

Educative Answers Team

A linked list is a common data structure made up of a chain of nodes in which each node contains a value and a pointer to the next node in the chain. Linked lists can dynamically increase/decrease in size – it is easy to insert and delete from a linked list.

The linked list data structure is available in the built-in List class.

Removing duplicates

In order to remove duplicates from a linked list, we will use the C# built-in function Distinct().toList(), which returns a new list after removing all duplicates from a specified list.

Remember to include System.Linq before using this function.

svg viewer

Code

using System;
using System.Collections.Generic;
using System.Linq;


class RemoveDuplicates
{
    static void Main()
    {
      //List
      List<int> lst = new List<int>();
      lst.Add(1);
      lst.Add(2);
      lst.Add(3);
      lst.Add(3);

      System.Console.WriteLine("List with duplicates:");
      lst.ForEach(Console.WriteLine); 

      // Distinct().toString() method
      List<int> uniqueLst =lst.Distinct().ToList();
      
      System.Console.WriteLine("List after removing duplicates:");
      uniqueLst.ForEach(Console.WriteLine);
    }
}

RELATED TAGS

c#
linked list
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring