2011-12-06 14 views
4

私はDictionary<string, int>を持っていて、リストからいくつかの文字列を読んでいます...辞書に追加したいのですが、文字列がすでに辞書に入っていれば、その値を1だけ増やしたい辞書<string, int>増加値

私が試したコードは以下の通りですが、入力ごとに増加する文字列がいくつかあります。間違っていますか?

Dictionary<string, int> dictionary = new Dictionary<string, int>(); 
    foreach (String recordline in tags) 
    { 
     String recordstag = recordline.Split('\t')[1]; 
     String tagToDic = recordstag.Substring(0, (recordstag.Length-1)); 

     if (dictionary.ContainsKey(tagToDic) == false) 
     { 
      dictionary.Add(tagToDic, 1); 
     } 
     else 
     { 

      try 
      { 
       dictionary[tagToDic] = dictionary[tagToDic] + 1; 
      } 
      catch (KeyNotFoundException ex) 
      { 
       System.Console.WriteLine("X" + tagToDic + "X"); 
       dictionary.Add(tagToDic, 1); 
      } 
     } 
    } 

EDITは:それは常に空白ですので、私は、文字列の最後の文字を削除しています...あなたのコメントに答えるために... 私の入力は次のようである:

10000301 business 0 0,000 
10000301 management & auxiliary services  0 0,000 
10000316 demographie  0 0,000 
10000316 histoire de france 0 0,000 
10000347 economics 0 0,000 
10000347 philosophy 1 0,500 

と私"ビジネス"または "管理&補助サービス"のような文字列だけを必要とします。

+2

何が価値があるのは、あなたのコードをクリーンアップすることができますについて*たくさん*:http://codepad.org/3DD4H1zl – Ryan

+6

サンプル入力をあなたが見ている動作を示す文字列? –

+1

あなたの質問を明確にするために操作しようとしている文字列の例を挙げてください。 – lafama

答えて

2

このLinqクエリを使用して解決することができる辞書の必要はありません。

var q = 
    from s in tags.Select (t => t.Substring(t.IndexOf("\t"))) 
    group s by s into g 
    select new 
    { 
     g.Key, 
     Count = g.Count() 
    }; 

(あなたが\t後に完全な文字列をしたいと仮定)そして、あなたは辞書として、それを必要とする場合にだけ追加します。

var dic = q.ToDictionary (x => x.Key, x => x.Count); 
1

をご入力文字列が最初を分割し、その後のサブそれはtagToDicに戻ったので、おそらくn個の文字列にはと同じ tagToDicがあります。

0

既存の値からカウントを取得した後は、辞書値を再追加するほうが簡単でしょう。

ここでは、ルックアップロジックを処理するための擬似コードがあります。

Dictionary<string, int> _dictionary = new Dictionary<string, int>(); 

private void AdjustWordCount(string word) 
{ 

    int count; 
    bool success = _dictionary.TryGetValue(word, out count); 

    if (success) 
    { 
    //Remove it 
    _dictionary.Remove(word); 
    //Add it back in plus 1 
    _dictionary.Add(word, count + 1); 
    } 
    else //could not get, add it with a count of 1 
    { 
    _dictionary.Add(word, 1); 
    } 
} 
0

方法について:リストでそれらを持っている場合

Dictionary<string, int> dictionary = new Dictionary<string, int>(); 
string delimitedTags = "some tab delimited string"; 
List<string> tags = delimitedTags.Split(new char[] {'\t'}, StringSplitOptions.None).ToList(); 
foreach (string tag in tags.Distinct()) 
{ 
    dictionary.Add(tag, tags.Where(t => t == tag).Count()); 
} 
0

あなただけのグループにそれらができ、あなたのリストを作ります。

list.GroupBy(recordline => recordline.Split('\t').Substring(0, (recordstag.Length-1), 
    (key, ienum) => new {word = key, count = ienum.Count()}); 

次に、それを辞書に入れたり、繰り返したりできます。

0

dictionaryコードは期待通りに機能するように見えます。

私の推測では、文字列分割コードが正しく機能していないと思います。
これを確認するには、サンプル入力が必要です。

とにかく、コードのあなたの全体のブロックを簡略化し、LINQを書き換えることができます:あなたは、入力文字列配列内の各文字列を分割して、文字列配列の第二の文字列を選択している

var dictionary = tags 
    .Select(t => { 
     var recordstag = t.Split('\t')[1]; 
     return recordstag.Substring(0, recordstag.Length-1); 
    }) 
    .GroupBy(t => t) 
    .ToDictionary(k => k.Key, v => v.Count()) 
    ; 
+0

私は 'recordstag.Substring(0、recordstag.Length-1); 'の必要性を理解していません。なぜ最後の文字を削除するのですか? – Kash

+2

@カッシュ私は知らない、なぜあなたは私に尋ねているのですか? @SpDaglasにお尋ねください! –

+0

しました。あなたがそれについての洞察を持っているかどうか疑問に思っていました。 – Kash

6

次に、SubStringを使用してこの2番目の文字列の最後の文字を削除します。したがって、最後の文字だけが異なるすべての文字列は同じとみなされ、インクリメントされます。それで、なぜあなたは "すべての入力で増加するいくつかの文字列"を見ているかもしれません。

EDIT:最後の文字を削除する目的がスペースを削除する場合は、代わりにString.Trimを使用します。 もう1つの編集では、値をインクリメントするのに適したContainsKeyの代わりにTryGetValueを使用しています。コードは以下で編集されています。

これを試してみてください:

Dictionary<string, int> dictionary = new Dictionary<string, int>(); 
    foreach(string recordline in tags) 
    { 
     string recordstag = recordline.Split('\t')[1].Trim(); 
     int value; 
     if (!dictionary.TryGetValue(recordstag, out value)) 
     dictionary.Add(recordstag, 1); 
     else 
     dictionary[recordstag] = value + 1; 
    } 
0

拡張メソッド

public static void Increment(this Dictionary<string, int> dictionary, string key) 
{ 
    int val; 
    dictionary.TryGetValue(key, out val); 
    if (val != null) 
     dictionary[key] = val + 1; 
} 

Dictionary<string, int> dictionary = new Dictionary<string, int>(); 
// fill with some data 

dictionary.Increment("someKey"); 
関連する問題