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());
}
}
}
Use the Distinct() method to remove duplicates from a list in C#.
colorList = colorList.Distinct().ToList();
foreach (string color in colorList.Distinct())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With