Skip to main content
 首页 » 编程设计

c#之计算一个项目在列表中出现的次数 C#

2024年02月13日10birdshome

假设允许用户从列表框中选择一支球队,点击一个按钮并通过引用.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! ") 
}