Avoid Adding duplicate elements to a List C#
asp.net, asp.net-mvc, c#, c#-4.0, list
Solution
Your this check:
if (!lines2.Contains(lines3.ToString()))
is invalid. You are checking if your `lines2` contains `System.String[]` since `lines3.ToString()` will give you that. You need to check if item from `lines3` exists in `lines2` or not.
You can iterate each item in `lines3` check if it exists in the `lines2` and then add it. Something like.
foreach (string str in lines3)
{
if (!lines2.Contains(str))
lines2.Add(str);
}
Or if your `lines2` is any empty list, then you can simply add the `lines3` distinct values to the list like:
lines2.AddRange(lines3.Distinct());
then your `lines2` will contain distinct values.
Problem
``` string[] lines3 = new string[100]; List<string> lines2 = new List<string>(); lines3 = Regex.Split(s1, @"\s*,\s*"); if (!lines2.Contains(lines3.ToString())) { lines2.AddRange(lines3.Distinct().ToArray()); } ``` I have checked all the spaces etc but i still get duplicate values in my lines2 `List` I have to remove my duplicate values here itself