我是C#的新手,我不得不停止使用IEnumerable.Except。我想要做的是使用2个模具获得100个随机骰子卷的2个序列的差异。我有我的掷骰子和总数很好去。我的差异根本没有显示在我的txtDifference文本框中。我不确定我是否将它放在正确的位置或者是否没有正确写入。代码本身没有错误,我不知道如何解决它。这是我的代码,非常感谢任何帮助!
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();
}
答案 0 :(得分:3)
txtDifference.Text = number.ToString();
将仅显示集合中的最后一个数字,因为您将覆盖每次迭代的值。
我认为您正在寻找所有值:
txtDifference.Text = String.Join(",", onlyInFirstSet);
答案 1 :(得分:1)
两个循环从1迭代到100.然后,在这两种情况下,您都要将i
的值添加到列表中...这意味着两个列表最终都以1到100的值结束它们。
numbers.Add(i);
secondNumbers.Add(i);
因此,以下代码行始终会生成一个空列表。它从第一个数字1到100的集合中删除第一个数字1到100的集合。
IEnumerable<int> onlyInFirstSet = numbers.Except(secondNumbers);
相反,请将rollValue
值添加到列表中,而不是foreach
循环迭代的变量:
rollValue = die1 + die2;
//add to collection.
numbers.Add(rollValue);
第二个循环和集合也是如此:
rollValue = die1 + die2;
//add to collection.
secondNumbers.Add(rollValue);