按等级顺序显示文本文件中的行
问题描述:
答
快速“N”简单的方法是使用一个Dictionary
和循环:
using(StreamReader sr = new StreamReader("my file")) {
Dictionary<string, int> items = new Dictionary<string, int>();
while(sr.BaseStream.Position < sr.BaseStream.Length) {
string s = sr.ReadLine();
if(items.ContainsKey(s)) {
items[s]++;
} else {
items.Add(s, 1);
}
}
// You now have a dictionary of unique strings and their counts - you can sort it however you need.
}
答
如果文件不是太大,也就是说,如果它可以存放在内存中,您可以将其存储在一本字典。
做“文字线”的字典 - >
读取文件中的行同时“的,它已经看到的次数”。如果该行已经在字典中,则将字典值加1。如果该行是新行,请将其添加到字典中并将值设置为1。
读取完整个文件后,可以取出键/值。按值排序以查找最常出现的值并打印结果。
答
为.NET框架3.0的代码:
using System;
using System.IO;
using System.Collections.Generic;
public class Program
{
private static int Compare(KeyValuePair<string, int> kv1, KeyValuePair<string, int> kv2)
{
return kv2.Value == kv1.Value ? kv1.Key.CompareTo(kv2.Key) : kv2.Value - kv1.Value;
}
public static void Main()
{
Dictionary<string, int> histogram = new Dictionary<string, int>();
using (StreamReader reader = new StreamReader("Test.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (histogram.ContainsKey(line))
++histogram[line];
else
histogram.Add(line, 1);
}
}
List<KeyValuePair<string, int>> sortedHistogram = new List<KeyValuePair<string, int>>(histogram);
sortedHistogram.Sort(Compare);
foreach (KeyValuePair<string, int> kv in sortedHistogram)
Console.WriteLine("{0}\t{1}", kv.Value, kv.Key);
}
}
的Test.txt:
ddd
aaa
ccc
bbb
aaa
aaa
bbb
输出:
3 aaa
2 bbb
1 ccc
1 ddd
我不能用这个 - 框架4.0? – qwertyuywertwer 2011-12-19 00:49:02
是的 - 对不起,我修正了这个:)请现在测试它 – kol 2011-12-19 00:54:20
我不得不删除LINQ部分,它出现在.NET 3.5中 – kol 2011-12-19 00:59:18