Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 241
Rob Avatar asked Oct 25 '12 21:10

Rob


People also ask

How do you find duplicate values in an array?

Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.

How do you find duplicate numbers in an array if it contains multiple duplicates?

Simple Approach: The idea is to use nested loop and for each element check if the element is present in the array more than once or not. If present, then store it in a Hash-map.


2 Answers

One simple approach is via LINQ:

bool allUnique = Numbers.Distinct().Count() == Numbers.Length;
like image 97
Jon Skeet Avatar answered Oct 06 '22 23:10

Jon Skeet


Another approach is using a HashSet<string>:

var set = new HashSet<string>(Numbers);
if (set.Count == Numbers.Count)
{ 
    // all unique
}

or with Enumerable.All:

var set = new HashSet<string>();
// HashSet.Add returns a bool if the item was added because it was unique
bool allUnique = Numbers.All(text=> set.Add(text)); 

Enunmerable.All is more efficient when the sequence is very large since it does not create the set completely but one after each other and will return false as soon as it detects a duplicate.

Here's a demo of this effect: http://ideone.com/G48CYv

  • HashSet constructor memory consumption: 50 MB, duration: 00:00:00.2962615
  • Enumerable.All memory consumption: 0 MB, duration: 00:00:00.0004254

msdn

The HashSet<T> class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

like image 2
Tim Schmelter Avatar answered Oct 06 '22 23:10

Tim Schmelter