IntroductionThis is very simple snippets to remove the duplicate or repeating element in generic list using C#. The Generic list is good collection to support multiple data type and reduce the casting operation.In one my project I have been use the generic list for keep the few object with different types. But sometime elements are repeating in list. So I have created a method to remove the repeating element from list. Implementationusing System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Utility
{
public static List<T> RemoveRepeatElement<T>(List<T> source)
{
Dictionary<T, int> listofUniqueElement = new Dictionary<T, int>();
List<T> listofdest = new List<T>();
foreach (T item in source)
{
if (!listofUniqueElement.ContainsKey(item))
{
listofdest.Add(item);
listofUniqueElement.Add(item, 0);
}
}
return listofdest;
}
}
}
In above method I have been used Dictionary to keep the unique element as key to check every element with looping. If an element not found inside the dictionary, then I will add that into Dictionary and new List as well. finally return new list. How to use?using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> collectionOfSource = new List<string>();
collectionOfSource.Add("RRaveen");
collectionOfSource.Add("John");
collectionOfSource.Add("RRaveen");
collectionOfSource.Add("Kumar");
collectionOfSource.Add("Dhana");
Console.WriteLine("Source:");
Console.WriteLine("---------------------------------");
foreach (string var in collectionOfSource)
{
Console.WriteLine(var);
}
List<string> collectionOfremoved = Utility.RemoveRepeatElement(collectionOfSource);
Console.WriteLine("Duplicate removed collection:");
Console.WriteLine("---------------------------------");
foreach (string var in collectionOfremoved)
{
Console.WriteLine(var);
}
Console.ReadLine();
}
}
}
Output Source:
---------------------------------
RRaveen
John
RRaveen
Kumar
Dhana
Duplicate removed collection:
---------------------------------
RRaveen
John
Kumar
Dhana
Hopes help.thank you for reading. |