簡體   English   中英

字典 <string, int> 增加價值

[英]Dictionary<string, int> increase value

我有一個Dictionary<string, int> ,我正在從列表中讀取一些字符串...我想在字典中添加它們,但如果字符串已經在字典中,我希望它的值增加1。

我嘗試的代碼如下所示,但是有一些字符串隨着每個輸入而增加..是不是有問題?

    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);
            }
        }
    }

編輯:回答你的評論...我刪除字符串的最后一個字符,因為它總是一個空格...我的輸入如下:

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

我只想要像“業務”或“管理和輔助服務”等字符串。

您正在拆分輸入字符串數組中的每個字符串並選擇字符串數組中的第二個字符串。 然后,您將使用SubString刪除此第二個字符串的最后一個字符 因此,僅在最后一個字符中不同的所有字符串將被視為相同且遞增。 這就是為什么你可能會看到“隨着每次輸入而增加的一些字符串”。

編輯:如果刪除最后一個字符的目的是刪除空格,請改用Use.Trim。 另一個編輯是使用TryGetValue而不是ContainsKey,它可以更好地增加您的值。 代碼編輯如下。

嘗試這個:

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

不需要字典,可以使用此Linq查詢來解決。
(假設你想要\\t之后的完整字符串)

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()
    };

如果你需要它作為字典,只需添加:

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

您的輸入字符串首先拆分 ,然后它的子字符串返回到tagToDic,所以也許n個字符串具有相同的 tagToDic。

擴展方法

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");

從現有計數中檢索計數后,重新添加字典值可能更容易。

這里有一些用於處理查找邏輯的偽代碼。

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);
  }
}

怎么樣:

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());
}

如果您將它們放在列表中,您可以將它們分組並制作列表。

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

然后你可以把它放在字典中或迭代它或什么的。

您的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())
    ;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM