DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

Program to remove duplicate values from a generic list using C# and VB.NET

By Ashok Nalam on 14 Apr 2014 | Category: LINQ | Tagged: linq enumerable generics list C# VB.NET 
This snippet shows how to remove duplicate values from a generic list.
  Discuss Add Comment   |  
Add rating Rate this resource   

Introduction

This snippet shows how to remove duplicate values from a generic List<T>. We can remove duplicates values from list using Enumerable.Distinct() method.

C# Program:

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

namespace DotNetMirror
{
    class RemoveDuplicatesList
    {
        public static void Main()
        {
            List<int> numbers = new List<int> { 1, 1, 2, 3, 5, 2, 4, 3, 4 };
            List<int> distinctNumbers = numbers.Distinct().ToList(); //Returns distinct elements from a sequence
            foreach (int i in distinctNumbers)
            {
                Console.WriteLine(i);
            }
            Console.ReadLine();
        }
    }
}

VB.NET Program:

Imports System.Linq
Imports System.Collections.Generic

Namespace DotNetMirror
    Class RemoveDuplicatesList
        Public Shared Sub Main()
            Dim numbers As New List(Of Integer)() From {1, 1, 2, 3, 5, 2, 4, 3, 4}
            Dim distinctNumbers As List(Of Integer) = numbers.Distinct().ToList()'Returns distinct elements from a sequence
            For Each i As Integer In distinctNumbers
                Console.WriteLine(i)
            Next
            Console.ReadLine()
        End Sub
    End Class
End Namespace

Output

1
2
3
5
4

Note: If you want to order as well use 

numbers.Distinct().OrderBy(x => x).ToList()

  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9226  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (0)
No comments found, click here to add comment.
 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys