C# Removing Duplicates from List
Remove duplicate strings from a List in C#, the old way with Sort and RemoveAt and the shorter way with Distinct.
Two ways to remove duplicates from a list of strings.
Old fashioned
Sort the list, then remove an item whenever it matches the next one.
csharp
List<string> strlist = new List<string>();
//Fill the list with random values
strlist.Sort();
Int32 index = 0;
while (index < strlist.Count - 1)
{
if (strlist[index] == strlist[index + 1])
strlist.RemoveAt(index);
else
index++;
}
New way
LINQ does it in one line.
csharp
var newlist = strlist.Distinct().ToList();