I have this code:
private void test(List<string> a)
{
}
I want to use for in for loop's and to check that if there are duplicated items in the List a Then mark it with null.
I have this code:
private void test(List<string> a)
{
}
I want to use for in for loop's and to check that if there are duplicated items in the List a Then mark it with null.
Not sure exactly what you want to do here but if you wanted to just get a collection of the distinct values in the list you could use LINQ to do this:
var distinctOnes = a.Distinct();
Loop through the strings and put new strings in a HashSet so that you can efficiently check for repeats:
var set = new HashSet<string>();
for (int i = 0; i < a.Count; i++) {
if (set.Contains(a[i])) {
// duplicate
a[i] = null;
} else {
set.Add(a[i]);
}
}
You should really avoid methods with side effects Side Effects Answer. You can achieve what you want like this:
private List<String> test(List<String> originalList)
{
List<String> returnList = new ArrayList<String>();
for (String value : originalList)
{
if (!returnList.contains(value))
{
returnList.add(value);
}
}
return returnList;
}
You can easily amend this method to add null as well if you really wanted to (instead of not adding anything if its already been added)...
private bool HasDuplicates(List<string> a)
{
return a.Distinct().Count() != a.Count();
}
you can use LINQ
var list = (from n in a select n).Distinct().ToList();
so know you have a unique list that you can check against "a"