我创建一个应用程序,根据单词计数的结果填充30个文本框。
最终版本将包含30个单词,但此测试仅包含3个
你怎么把它变成循环?
int[] totX = new int[30];
string nav1 = "test1";
string nav2 = "test2";
string nav3 = "test3";
public Form1()
{
using (StreamReader sr = new StreamReader(@"c:\temp\output.txt"))
{
var total = 0;
while (!sr.EndOfStream)
{
var counts = sr
.ReadLine()
.Split('"')
.GroupBy(s => s)
.Select(g => new { Word = g.Key, Count = g.Count() });
var wc = counts.SingleOrDefault(c => c.Word == nav1);
total += (wc == null) ? 0 : wc.Count;
totX[0] = total;
}
}
using (StreamReader sr = new StreamReader(@"c:\temp\output.txt"))
{
var total = 0;
while (!sr.EndOfStream)
{
var counts = sr
.ReadLine()
.Split('"')
.GroupBy(s => s)
.Select(g => new { Word = g.Key, Count = g.Count() });
var wc = counts.SingleOrDefault(c => c.Word == nav2);
total += (wc == null) ? 0 : wc.Count;
totX[1] = total;
}
}
using (StreamReader sr = new StreamReader(@"c:\temp\output.txt"))
{
var total = 0;
while (!sr.EndOfStream)
{
var counts = sr
.ReadLine()
.Split('"')
.GroupBy(s => s)
.Select(g => new { Word = g.Key, Count = g.Count() });
var wc = counts.SingleOrDefault(c => c.Word == nav3);
total += (wc == null) ? 0 : wc.Count;
totX[2] = total;
}
}
InitializeComponent();
}
private void button1_Click_1(object sender, EventArgs e)
{
textBox1.Text = totX[0].ToString();
textBox2.Text = totX[1].ToString();
textBox3.Text = totX[2].ToString();
}
}
}
答案 0 :(得分:2)
围绕流进行常规for循环,并将计数器用作totX数组中的索引。也可以在每次迭代期间创建导航字符串。
此外,实际上不需要读取相同的文件30次,因此我建议您阅读该文件一次,然后根据需要检查内容。
答案 1 :(得分:0)
int[] totX = new int[3];
string[] navX = new string[] {"test1", "test2", "test3"};
public Form1()
{
for (int i = 0; i < 3; i++)
{
using (StreamReader sr = new StreamReader(@"c:\temp\output.txt"))
{
var total = 0;
while (!sr.EndOfStream)
{
var counts = sr
.ReadLine()
.Split('"')
.GroupBy(s => s)
.Select(g => new { Word = g.Key, Count = g.Count() });
var wc = counts.SingleOrDefault(c => c.Word == navX[i]);
total += (wc == null) ? 0 : wc.Count;
totX[i] = total;
}
}
}
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = totX[0].ToString();
textBox2.Text = totX[1].ToString();
textBox3.Text = totX[2].ToString();
}
}