Jimmy Liang
Jimmy Liang

Reputation: 13

Counting the number of times a team name has occurred in a list and putting the answer in a listbox

So I have to make a method that takes a list of baseball teams in order of the year they have won the world series. I am trying to enter into a list box the number of times a certain team has won the world series using an array/dictionary.

    private void btnTrivia_Click(object sender, EventArgs e)
    {
        int counter = 0;
        string line;
        System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\t\Documents\Visual Studio 2013\Projects\Assignment_6_Testing\Assignment_6_Testing\Assignment6TestProject\WorldSeriesWinners.txt");
        List<string> list = new List<string>();
        while ((line = file.ReadLine()) != null)
        {

            list.Add(line);
            counter++;

        }

        string[] arr = list.ToArray();
        var dict = new Dictionary<string,int>();


        foreach (string item in arr)
        {
            if (dict.ContainsKey(item))
            {

                dict[item] += 1;

            }
            else
            {
                dict.Add(item, 1);
            }

            //Although it's incorrect, what I want next is to have something like this:
            foreach (var team in dict)
            {
                if (dict.Values.Contains("New York Yankees"))
                {
                    listbox.Items.Add(//New York Yankees have won 27 times)
                }

            }

            }

        }

Upvotes: 0

Views: 118

Answers (1)

Save
Save

Reputation: 11938

All you need can be nicely done using LINQ:

    var dict = arr
        .GroupBy(x => x)
        .Where(x => selectedTeams.Contains(x))
        .ToDictionary(x => x.Key, x => x.Count());

Upvotes: 1

Related Questions