假设允许用户从ListBox中选择一个团队,单击一个按钮并显示该团队通过引用.txt文件(称为World Series)赢得World Series的次数。
我正在尝试获取所选项目,并检查所选项目在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.")
}
}
答案 0 :(得分:2)
if (teamList.SelectedIndex == -1)
{
MessageBox.Show("Please select an Item first!");
return;
}
string selectedTeam = teamList.SelectedItem.ToString();
var count = File.ReadAllLines("WorldSeries.txt").Where(line => line ==selectedTeam).Count();
//var count = champList.Where(l=>l==selectedTeam).Count();
if (count >0)
{
MessageBox.Show("The " + selectedTeam + "has won the World Series " + count + "times! ");
}
else
{
MessageBox.Show("The " + selectedTeam + "has never won the World Series.")
}
答案 1 :(得分:2)
您可以使用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! ")
}
答案 2 :(得分:0)
你可以这样做
if(teamList.SelectedIndex != 0 && champList.Contains(SelectedTeam))
{
MessageBox.Show("The " + selectedTeam + "has won the World Series " + champList.Where(w => w == SelectedItem).Count() + "times! ");
}
答案 3 :(得分:0)
将champList放在字典中并增加一个计数器(如果它们已经存在)。
private void compareList()
{
StreamReader champFile = File.OpenText("WorldSeries.txt");
Dictionary<string, int> champList = new Dictionary<string, int>();
string selectedTeam;
string currentChamp;
while (!champFile.EndOfStream)
{
currentChamp = champFile.ReadLine();
if(champList.containsKey(currentChamp))
champList.get(currentChamp) += 1;
else
champList.Add(champFile.ReadLine(), 1);
}
while (teamList.SelectedIndex != 0)
{
selectedTeam = teamList.SelectedItem.ToString();
}
if (champList.hasKey(selectedTeam))
{
MessageBox.Show("The " + selectedTeam + "has won the World Series " + champList.get(selectedTeam) + "times! ")
}
else
{
MessageBox.Show("The " + selectedTeam + "has never won the World Series.")
}
}