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; }
I suggest processing the values: removing empty / all whitespaces strings, leading and trailing spaces at least (note, that "3 " != " 3" != "3"
):
new Char[] { '\n', '\r' }
note \r
can appear as a new line; let's be on the safer side of the road.Where(item => !string.IsNullOrWhiteSpace(item))
we don't want all whitespaces line (empty lines included) like " "
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;
}