计算队列名称在列表中出现的次数,并将答案放入列表框中

时间:2015-07-22 19:48:23

标签: c#

所以我必须制作一个方法,按照他们赢得世界系列赛的年份排列棒球队名单。我试图进入一个列表框,表示某个团队使用数组/字典赢得世界系列赛的次数。

    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)
                }

            }

            }

        }

1 个答案:

答案 0 :(得分:1)

使用LINQ可以很好地完成所有工作:

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