Reputation: 33
I making a lottery simulation and i have 2 different arrays with 6 numbers to hold firstly the numbers the user wishes to play and secondly the numbers that get generated each run.
The user enters their numbers into a textbox and its saved as a string and placed into respective spots in the aray, the randomly generated nums are also saved as a string into the string array.
After this i have a SequenceEqual for comparison
bool equal = lotteryNums.SequenceEqual(playerNums);
This always returns false, i have set all the generated array elements manually to 1-6 and then the players nums accordingly through the textboxes yet it will always return a false.
The generated array is currently filled like this for testing
lotteryNums[0] = "1";
lotteryNums[1] = "2";
lotteryNums[2] = "3";
lotteryNums[3] = "4";
lotteryNums[4] = "5";
lotteryNums[5] = "6";
The player array is filled like this using the next array position for the next number
string inputNum = inputBox_txt.Text;
playerNums[0] = inputNum;
Why is this always returning false?
Since people are asking the arrays are both in the exact same order and do not appear to contain anything more or anything less than the numbers in the arrays
Upvotes: 2
Views: 1764
Reputation: 37000
SeqqnceEqual
will also take the order of the elemnts into account, which you probably don´t want in a lottery. What you want instead is to check if all the expected values are in the inout as well:
var sixCorrects = lotteryNums.All(x => playerNums.Contains(x));
All
will stop iterating as soon as an element of lotteryNums
was not found within playerNums
.
Upvotes: 0
Reputation: 825
Another thing to consider: SequenceEquals
requires that the numbers be in the exact same order in both arrays. Even if the arrays contain the same numbers, but they are in a different order, you will get false. You can solve this by sorting each list prior to comparing (just make sure you sort both in the same way).
If that doesn't work, verify that the strings from the textbox are actually just the numbers, and do not include any white space or special characters.
Upvotes: 0
Reputation: 1438
In addition to what Athanasios Emmanouilidis said: it seems that the collections need to have the same order. So you should order them:
bool equal = playerNums.OrderBy(n => n).SequenceEqual(lotteryNums.OrderBy(n => n));
Upvotes: 2
Reputation: 2144
SequenceEqual
returns true if the two source sequences are of equal length and their corresponding elements are equal according to the default equality comparer for their type; otherwise, false.
Since the two arrays you provide are not identical then you are getting false
.
Upvotes: 3