Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates from a List<string> in C# [duplicate]

Tags:

c#

list

asp.net

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());
                    }
        }
    }
like image 816
Hamamelis Avatar asked Sep 17 '14 11:09

Hamamelis


People also ask

How do I remove duplicates from a list in C sharp?

Use the Distinct() method to remove duplicates from a list in C#.


2 Answers

colorList = colorList.Distinct().ToList();
like image 101
Eren Ersönmez Avatar answered Oct 04 '22 21:10

Eren Ersönmez


foreach (string color in colorList.Distinct())
like image 23
Selman Genç Avatar answered Oct 04 '22 22:10

Selman Genç