12

Remove duplicates from a List in C#

I have a data reader to read the string from database.

I use the List for aggregate the string read from database, but I have duplicates in this string.

Anyone have a quick method for remove duplicates from a generic List in C#?

List<string> colorList = new List<string>();

    public class Lists
    {
        static void Main()
        {
            List<string> colorList = new List<string>();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            colorList.Add(variableFromDB.ToString());

                    foreach (string color in colorList)
                    {
                      Response.Write(color.ToString().Trim());
                    }
        }
    }
Hamamelis
  • 1,983
  • 8
  • 27
  • 41

4 Answers4

51
colorList = colorList.Distinct().ToList();
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92
5
foreach (string color in colorList.Distinct())
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
4
IEnumerable<Foo> distinctList = sourceList.DistinctBy(x => x.FooName);

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector)
{
    var knownKeys = new HashSet<TKey>();
    return source.Where(element => knownKeys.Add(keySelector(element)));
}
Dgan
  • 10,077
  • 1
  • 29
  • 51
3

Using LINQ:

var distinctItems = colorList.Distinct();

Similar post here: Remove duplicates in the list using linq

Community
  • 1
  • 1
Godspark
  • 354
  • 2
  • 13