5

I have a text box that has each item on a new line. I am trying to remove duplicates from this textBox. I can't think of anything. I tried adding each item to an array and the removing the duplicates, but it doesn't work. Are there any other options?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Jeremy
  • 93
  • 3
  • 6
  • 2
    " I tried adding each item to an array and the removing the duplicates, but it doesn't work" - what doesn't work? No one here got batteries with their xmas crystal balls... – Mitch Wheat Jan 01 '11 at 02:21
  • 2
    If adding each item to an array and removing the duplicates didn't work, it's because you didn't do it right. Please note that when asking someone to help figure out why what you did wouldn't work, it's customary to show what it is you did. – Jonathan Wood Jan 01 '11 at 02:24

3 Answers3

7
yourTextBox.Text = string.Join(Environment.NewLine, yourArray.Distinct());
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
4

Building on what Anthony Pegram wrote, but without needing a separate array:

yourTextBox.Text = string.Join(Environment.NewLine, yourTextBox.Lines.Distinct());

CSharper
  • 236
  • 1
  • 3
1

Add all the Items to string array and use this code to remove duplicates

public static string[] RemoveDuplicates(string[] s)
{
    HashSet<string> set = new HashSet<string>(s);
    string[] result = new string[set.Count];
    set.CopyTo(result);
    return result;
}

For more information have a look at Remove duplicates from array

Community
  • 1
  • 1
Tasawer Khan
  • 5,994
  • 7
  • 46
  • 69