字典<string,int =“”>增加值</string,>

时间:2011-12-06 20:10:51

标签: c# dictionary

我有一个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

我只想要像“商业”或“管理和辅助服务”等字符串。

8 个答案:

答案 0 :(得分:6)

您正在拆分输入字符串数组中的每个字符串,并选择字符串数组中的第二个字符串。 然后使用SubString 删除第二个字符串的最后一个字符。因此,仅在最后一个字符中不同的所有字符串将被视为相同且递增。这就是为什么你可能会看到“一些字符串随着每次输入而增加”。

编辑:如果删除最后一个字符的目的是删除空格,请使用String.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;
    }

答案 1 :(得分:2)

不需要字典,可以使用此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);

答案 2 :(得分:1)

您的输入字符串首先拆分,然后子字符串返回到tagToDic,所以n个字符串可能有相同的 tagToDic。

答案 3 :(得分: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);
  }
}

答案 4 :(得分: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());
}

答案 5 :(得分:0)

如果您将它们放在列表中,则可以将它们分组并制作列表。

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

然后你可以将它放在字典中或迭代它或其他东西。

答案 6 :(得分: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())
    ;

答案 7 :(得分: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");