6

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,869
  • 8
  • 26
  • 40

4 Answers4

41
colorList = colorList.Distinct().ToList();
Eren Ersönmez
  • 37,498
  • 7
  • 66
  • 91
4
foreach (string color in colorList.Distinct())
Selman Genç
  • 97,365
  • 13
  • 115
  • 182
2

Using LINQ:

var distinctItems = colorList.Distinct();

Similar post here: Remove duplicates in the list using linq

Community
  • 1
  • 1
Godspark
  • 244
  • 2
  • 13
2
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
  • 9,618
  • 1
  • 28
  • 50