Skip to main content
 首页 » 编程设计

c#之IEnumerable.Except 在文本框 c sharp 中显示差异

2024年02月06日11shanyou

我是 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();  
    } 

请您参考如下方法:

txtDifference.Text = number.ToString(); 将仅显示集合中的最后一个数字,因为您将在每次迭代中覆盖该值。

我认为您正在寻找显示所有值的方法:

txtDifference.Text = String.Join(",", onlyInFirstSet);