2011-12-19 10 views
0

私はいくつかの行を含むテキストファイルを持っていますが、その多くは重複しています。テキストファイルの行をランク順に表示

一番上に表示されるものが一番上に表示され、一番小さいものが一番下に表示されるリストを描きたいと思います。

ただし、リスト内に文字列が何回表示されるかを表示したいとします。

どうすればいいですか?ファイルが大きすぎない場合には、それがメモリに収まることができれば、あなたがそれを保存することができ、すなわち、

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. 
} 

答えて

0

迅速な「n」の簡単な方法は、Dictionaryとループを使用することです辞書。

は、「テキストの行」の辞書を作る - >

は一度に行ファイルを読む「ことが見られていた回数」。行がすでに辞書に入っている場合は、辞書値を1だけインクリメントします。行が新しい場合は、辞書に追加して値を1に設定します。

ファイル全体を読み終えたら、キー/値を引き出すことができます。値でソートして最も出現した値を見つけ、結果を印刷します。

0

0

の.NET Framework 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 
+0

- フレームワーク4.0を? – qwertyuywertwer

+0

はい - 申し訳ありませんが、私はこれを修正します:) pls今すぐテストします – kol

+0

LINQの部分も削除しなければならなかったので、.NET 3.5で表示されました。 – kol

関連する問題