[csharp]
<SPAN style="FONT-FAMILY: Arial, Helvetica, sans-serif">Problem</SPAN>
Problem
Remove duplicates in a list
Solution
Sort the list.
Loop through the list. If the elements is not equal to last elements, that means a new element
[csharp]
using System;
using System.Collections.Generic;
namespace RemoveDuplicateInList
{
class Program
{
static void RemoveDuplicates(List<int> list)
{
if(list.Count <= 1){
return ;
}
list.Sort();
int tail = 0;
for (int i = 1; i < list.Count; ++i)
{
if (list[i] != list[tail])
{
list[++tail] = list[i];
}
}
tail++;
list.RemoveRange(tail, list.Count - tail);
}
static void Main(string[] args)
{
List<int> list = new List<int>();
Random random = new Random(100);
for (int i = 0; i < 41; i++)
{
list.Add(random.Next(0, 50));
}
Console.WriteLine("Before removing duplicate ");
foreach (int k in list)
{
Console.Write(" {0} ", k);
}
Program.RemoveDuplicates(list);
Console.WriteLine("\nAfter removing duplicates");
foreach (int k in list)
{
Console.Write(" {0} ", k);
}
Console.WriteLine();
}
}
}
using System;
using System.Collections.Generic;
namespace RemoveDuplicateInList
{
class Program
{
static void RemoveDuplicates(List<int> list)
{
if(list.Count <= 1){
return ;
}
list.Sort();
int tail = 0;
for (int i = 1; i < list.Count; ++i)
{
if (list[i] != list[tail])
{
list[++tail] = list[i];
}
}
tail++;
list.RemoveRange(tail, list.Count - tail);
}
static void Main(string[] args)
{
List<int> list = new List<int>();
Random random = new Random(100);
for (int i = 0; i < 41; i++)
{
list.Add(random.Next(0, 50));
}
Console.WriteLine("Before removing duplicate ");
foreach (int k in list)
{
Console.Write(" {0} ", k);
}
Program.RemoveDuplicates(list);
Console.WriteLine("\nAfter removing duplicates");
foreach (int k in list)
{
Console.Write(" {0} ", k);
}
Console.WriteLine();
}
}
}
Output
[csharp]
Before removing duplicate
48 7 33 45 17 47 35 30 17 7 48 26 18 24 48 24 44 49 19 1 5 19 44 48 25 42 45 32 8 30 5 39 25 24 28 4 43 26 23 36 13
Before removing duplicate
48 7 33 45 17 47 35 30 17 7 48 26 18 24 48 24 44 49 19 1 5 19 44 48 25 42 45 32 8 30 5 39 25 24 28 4 43 26 23 36 13 [csharp]
After removing duplicates
1 4 5 7 8 13 17 18 19 23 24 25 26 28 30 32 33 35 36 39 42 43 44 45 47 48 49
Press any key to continue . . .
After removing duplicates
1 4 5 7 8 13 17 18 19 23 24 25 26 28 30 32 33 35 36 39 42 43 44 45 47 48 49
Press any key to continue . . .