-6

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.

Daniel Lip
  • 3,867
  • 7
  • 58
  • 120
  • What do you mean by "mark it with null"? – Enigmativity Sep 13 '12 at 23:59
  • 2
    You might as well not have posted any code at all, as what you did post is meaningless. Voting to close this as "not a real question", as it shows zero effort to solve the problem yourself, and no research at all before posting it. – Ken White Sep 14 '12 at 00:07

5 Answers5

1

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();
itsmatt
  • 31,265
  • 10
  • 100
  • 164
0

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]);
  }
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

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)...

Community
  • 1
  • 1
ramsinb
  • 1,985
  • 12
  • 17
  • Rather than the (particularly inefficient) method, you could just use `return originalList.Distinct()`; – Servy Sep 14 '12 at 01:31
0
private bool HasDuplicates(List<string> a)
{
    return a.Distinct().Count() != a.Count();
}
armen.shimoon
  • 6,303
  • 24
  • 32
0

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"

Ehsan Zargar Ershadi
  • 24,115
  • 17
  • 65
  • 95
  • why do you have an identity select at the start of the query? Just call `list.Distinct()`. – Servy Sep 14 '12 at 01:32