Search code examples
c#countduplicatestextboxdistinct

c# check textbox for unique values


I have a textbox where user inputs values, each one in a new row, now i want to check if those input values are unique, but looks like it does not work if duplicated value is a last value, don't know why. Any tips? Lets say it is:

1
2
3
3

It will not work, but

1
2
3
3
5

Will work and show an error as duplicate

Here is a code i use: First I split textbox into array of strings

     string[] linesValues = textBoxValues.Text.Split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

then check for duplicates and show error

if (linesValues.Distinct().Count() != linesValues.Count()) { MessageBox.Show("Question values must be unique!", "Duplicated values found", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }

Solution

  • I suggest processing the values: removing empty / all whitespaces strings, leading and trailing spaces at least (note, that "3 " != " 3" != "3"):

    1. new Char[] { '\n', '\r' } note \r can appear as a new line; let's be on the safer side of the road
    2. .Where(item => !string.IsNullOrWhiteSpace(item)) we don't want all whitespaces line (empty lines included) like " "
    3. item => item.Trim() questions processing; let "3" be equal to "3 "

    Code:

    string[] linesValues = textBoxValues
      .Text
      .Split(new Char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries) 
      .Where(item => !string.IsNullOrWhiteSpace(item))
      .Select(item => item.Trim())
      .ToArray();
    

    and then check as you do

    using System.Linq;
    
    ...
    
    if (linesValues.Distinct().Count() != linesValues.Count()) { 
      MessageBox.Show("Question values must be unique!", 
                      "Duplicated values found", 
                       MessageBoxButtons.OK, 
                       MessageBoxIcon.Error); 
    
      return; 
    }