我试图计算文本文件每行第一个字符的出现次数。
示例文本文件:
A
抗体
AC
广告
乙
的Ba
示例输出:
A:4
B:2
这是我到目前为止的代码,问题是它不知道哪些字符是相同的,所以A,B,C,D等多次迭代... < / p>
string line;
char firstChar;
private void selectFile()
{
openFileDialog1.Title = "Open Text File";
openFileDialog1.Filter = "Text|*.txt";
openFileDialog1.InitialDirectory = @"C:\";
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
readFile();
}
}
private void readFile()
{
int counter = 0;
StreamReader readTxt = new StreamReader(openFileDialog1.FileName);
while ((line = readTxt.ReadLine()) != null)
{
charFreq();
counter++;
}
}
private void charFreq()
{
firstChar = line.ToCharArray()[0];
var charFreq =
from c in firstChar.ToString().ToCharArray()
group c by c into groupFrequencies
select groupFrequencies;
foreach (var c in charFreq)
rTxtOutput.Text += (String.Format("{0} : {1}", c.Key, c.Count())) + "\r\n";
}
这样做的正确方法是什么?谢谢!
答案 0 :(得分:3)
您可以使用LINQ&#39; GroupBy
:
var query = File.ReadLines(filePath).Where(line => !String.IsNullOrEmpty(line))
.GroupBy(line => line.First());
如果您想要考虑空行:
var query = File.ReadLines(filePath).GroupBy(line => line.FirstOrDefault());
因此该方法应如下所示:
void PrintCharCount(string filePath)
{
if (!String.IsNullOrEmpty(filePath))
{
var query = File.ReadLines(filePath).Where(line => !String.IsNullOrEmpty(line))
.GroupBy(line => line.First());
foreach (var g in query)
Console.WriteLine(g.Key + ": " + g.Count());
}
}
并且您不需要使用StreamReader
,File.ReadLines
是为LINQ设计的,因为它返回IEnumerable<string>
。