假设允许用户通过参考.txt文件(称为“世界大赛”)从列表框中选择一个球队,单击一个按钮并显示该队赢得世界大赛的次数。

我正在尝试获取选定的项目,并检查该选定的项目出现在World Series .txt文件中的次数。

有指针吗?

    private void compareList()
    {
        StreamReader champFile = File.OpenText("WorldSeries.txt");
        List<string> champList = new List<string>();
        string selectedTeam;

        while (!champFile.EndOfStream)
        {
            champList.Add(champFile.ReadLine());
        }
        while (teamList.SelectedIndex != 0)
        {
            selectedTeam = teamList.SelectedItem.ToString();
        }
        if (selectedTeam = champList???)
        {
            MessageBox.Show("The " + selectedTeam + "has won the World Series " + champList.????.Count + "times! ")
        }
        else
        {
            MessageBox.Show("The " + selectedTeam + "has never won the World Series.")
        }
    }

最佳答案

您可以使用File.ReadLines和一些LINQ

selectedTeam = teamList.SelectedItem.ToString();
var count = File.ReadLines("WorldSeries.txt")
           .Count(x => x.Contains(selectedTeam));


if(count > 0)
{
   MessageBox.Show("The " + selectedTeam + "has won the World Series " +  count + "times! ")
}

08-27 08:53