kyrosds
kyrosds

Reputation: 15

Comparing two list in C# using Linq and returning the duplicate numbers using user input from a numeric up and down box

I am trying to compare the two randomly generated lists, they need to compare the totals of the dice within the code and return the amount of duplicates of the number selected by the user. The user has a numeric up and down box to select the number between 1-12 and the program will return how many of the specified number is list between the two lists.

       int die1, die2;
        int[] roll1 = new int[101];
        int[] roll2 = new int[101];

        //set Array
        Random dice = new Random();

    private void DiceButton_Click_1(object sender, EventArgs e)
    {




        //sets value to the variables and for loop to generate 100 rolls
        for (int i = 1; i < 101; i++)
        {
            die1 = dice.Next(1, 7);
            die2 = dice.Next(1, 7);

            //displays picture of dice
            LblDie1.ImageIndex = die1;
            LblDie2.ImageIndex = die2;

            //displays roll in listbox
            roll1.SetValue(die1 + die2, i);
            listBox1.Items.Add(die1.ToString() + " + " + die2.ToString() + " = " + (die1 + die2).ToString() + "  Roll: " + i.ToString());
        }
        for (int i = 1; i < 101; i++)
        {
            die1 = dice.Next(1, 7);
            die2 = dice.Next(1, 7);

            //displays picture of dice
            LblDie1.ImageIndex = die1;
            LblDie2.ImageIndex = die2;

            //displays roll in listbox
            roll2.SetValue(die1 + die2, i);
            listBox2.Items.Add(die1.ToString() + " + " + die2.ToString() + " = " + (die1 + die2).ToString() + "  Roll: " + i.ToString());
        }
    }

    private void SearchButton_Click(object sender, EventArgs e)
    {
        var count = roll1.Intersect(roll2);

        foreach(var number in count)

            listBox4.Items.Add(count.ToString()); 
    }
}

}

Upvotes: 1

Views: 91

Answers (1)

yu_ominae
yu_ominae

Reputation: 2935

You get the elements of both list boxes, so you get two lists, say List1 and List2, then you do List1.Intersect(list2) and the result is a third list containing all common elements to both List1 and List2.

What you then do with the third list is up to you, but as I understand your question, this seems to be what you are looking for.

Have a look here for more information https://msdn.microsoft.com/en-us/library/vstudio/bb910215(v=vs.90).aspx

UPDATE

I see what you are trying to do now.

NumericUpDown has got a ValueChanged event. Use that to get the current value selected by the user, UserSelectedValue. If you want to know how many times the selected value occurs in both lists simultaneously, you can do something like List1.Count(UserSelectedValue) + List2.Count(UserSelectedValue), which should return how many times the value selected by the user has popped up in both lists

Upvotes: 1

Related Questions