by Edward
25 August 2010 08:05
There are many ways to remove duplicate elements from a generic List collection in the C# language, but some are easier to implement then other, or some might not fit your code. An easy solution, is using the LINQ extension methods can be very useful when you have a List collection. It is lightweight, and is can also be implemented anywhere in your solution.
For my example, I used the Linq "Distinct" method (System.Linq) to get a unique list of categories for books. I first get a list of my books from the database, and then use the "distinct" method, and then also cast the list back to a generic list with the duplicate items removed.
/// <summary>
/// Returns the distinct list of categories.
/// </summary>
/// <returns>List<string></returns>
private static List<string> ReturnDistinctListofCategories()
{
// List with duplicate elements.
List<string> list = new List<string>();
list.Add("code");
list.Add("coding");
list.Add("asp.net");
list.Add("tips");
list.Add("code");
list.Add("coding tips");
list.Add("asp.net tips");
// We now have a list with duplicate items
// Get distinct elements and convert into a list again.
List<string> distinctClientList = list.Distinct().ToList();
//DEBUG: Test the result
foreach (string value in distinctClientList)
{
Debug.WriteLine(value);
}
return distinctClientList;
}
I hope this can help you. Like I stated before, there are numerous ways to do the same as my code.