Rob Rob - 3 months ago 19
C# Question

How do I check for duplicate answers in this array? c#

Sorry for the newbie question. Could someone help me out? Simple array here. What's the best/easiest method to check all the user input is unique and not duplicated? Thanks

private void btnNext_Click(object sender, EventArgs e)
{

string[] Numbers = new string[5];


Numbers[0] = txtNumber1.Text;
Numbers[1] = txtNumber2.Text;
Numbers[2] = txtNumber3.Text;
Numbers[3] = txtNumber4.Text;
Numbers[4] = txtNumber5.Text;


foreach (string Result in Numbers)
{
lbNumbers.Items.Add(Result);
}

txtNumber1.Clear();
txtNumber2.Clear();
txtNumber3.Clear();
txtNumber4.Clear();
txtNumber5.Clear();
}
}


}

I should have added I need to check to happen before the numbers are output. Thanks

Answer

One simple approach is via LINQ:

bool allUnique = Numbers.Distinct().Count() == Numbers.Length;
Comments