I am new to C # and I am getting stuck on using IEnumerable.Except
. What I am trying to do is get the difference of 2 sequences of 100 random dice rolls using 2 die. I have my die rolls and totals good to go.
My differences are not showing in my txtDifference textbox at all. I am not sure if I have it placed in the correct spot or if it isn't written correctly. The code itself has no errors and I am not sure how to fix it. Here is my code, any help is greatly appreciated!!
private void btnRoll_Click(object sender, EventArgs e)
{
// create random and lists
randomizer = new Random();
List<int> numbers = new List<int>();
List<int> secondNumbers = new List<int>();
// for loop for 1st sequence
for (i = 1; i < 100; i++)
{
string mssg = string.Empty;
die1 = randomizer.Next(1, 7);
die2 = randomizer.Next(1, 7);
dieRoll1.Text = die1.ToString();
dieRoll2.Text = die2.ToString();
rollValue = die1 + die2;
// add to collection.
numbers.Add(i);
// display results
txtResults.Text += string.Concat(dieRoll1.Text, " ", dieRoll2.Text, " ", rollValue, " ", Environment.NewLine);
}
//loop for second sequence.
for (i = 1; i < 100; i++)
{
string mssg = string.Empty;
die1 = randomizer.Next(1, 7);
die2 = randomizer.Next(1, 7);
dieRoll1.Text = die1.ToString();
dieRoll2.Text = die2.ToString();
rollValue = die1 + die2;
//add to collection.
secondNumbers.Add(i);
//display results in second text box
txtResults2.Text += string.Concat(dieRoll1.Text, " ", dieRoll2.Text, " ", rollValue, " ", Environment.NewLine);
}
// IEnumerable for comparison between the two sequences
IEnumerable<int> onlyInFirstSet = numbers.Except(secondNumbers);
//foreach to display the differences between the sequences
foreach (int number in onlyInFirstSet)
txtDifference.Text = number.ToString();
}
Both loops iterate from 1 to 100. Then, in both cases, you're adding the value of i
to the lists... which means both lists end up with the values 1 to 100 in them.
numbers.Add(i);
secondNumbers.Add(i);
So the following line of code always results in an empty list. It removes the second collection of numbers 1 to 100 from the first collection of numbers 1 to 100.
IEnumerable<int> onlyInFirstSet = numbers.Except(secondNumbers);
Instead, add the rollValue
value to your list, not the variable your foreach
loop is iterating over:
rollValue = die1 + die2;
//add to collection.
numbers.Add(rollValue);
Same goes for your second loop and collection:
rollValue = die1 + die2;
//add to collection.
secondNumbers.Add(rollValue);