简体   繁体   English

字典 <string, int> 增加价值

[英]Dictionary<string, int> increase value

I have a Dictionary<string, int> and I am reading some strings from a list... I want to add them in the dictionary, but if the string is already in the dictionary, I want its value to increase by 1. 我有一个Dictionary<string, int> ,我正在从列表中读取一些字符串...我想在字典中添加它们,但如果字符串已经在字典中,我希望它的值增加1。

The code I tried is as below, but there are some strings that are increased with every input.. Is something wrong? 我尝试的代码如下所示,但是有一些字符串随着每个输入而增加..是不是有问题?

    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: To answer your comments... I am removing the last char of the string because it is always a blank space... My input is like: 编辑:回答你的评论...我删除字符串的最后一个字符,因为它总是一个空格...我的输入如下:

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

and i want only the string like "business" or "management & auxiliary services" etc. 我只想要像“业务”或“管理和辅助服务”等字符串。

You are splitting each string in the input string array and selecting the 2nd string in the string array. 您正在拆分输入字符串数组中的每个字符串并选择字符串数组中的第二个字符串。 Then you are removing the last character of this 2nd string using SubString . 然后,您将使用SubString删除此第二个字符串的最后一个字符 Hence all strings that differ only in the last character would be considered the same and incremented. 因此,仅在最后一个字符中不同的所有字符串将被视为相同且递增。 Thats why you might be seeing "some strings that are increased with every input". 这就是为什么你可能会看到“随着每次输入而增加的一些字符串”。

EDIT: If the purpose of removing the last char is to remove space, Use String.Trim instead. 编辑:如果删除最后一个字符的目的是删除空格,请改用Use.Trim。 Another edit is using TryGetValue instead of ContainsKey which performs better to increment your value. 另一个编辑是使用TryGetValue而不是ContainsKey,它可以更好地增加您的值。 Code has been edited below. 代码编辑如下。

Try this: 尝试这个:

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

No need for a dictionary, can be solved using this Linq query. 不需要字典,可以使用此Linq查询来解决。
(Assuming you want the complete string after \\t ) (假设你想要\\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()
    };

And if you need it as a dictionary just add: 如果你需要它作为字典,只需添加:

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

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

Extension method 扩展方法

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

It's probably easier just to re-add the dictionary value after you retrieve the count from the existing one. 从现有计数中检索计数后,重新添加字典值可能更容易。

Here's some psuedo code to handle the look up logic. 这里有一些用于处理查找逻辑的伪代码。

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

How about: 怎么样:

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

If you have them in a list you could just group them and make your list. 如果您将它们放在列表中,您可以将它们分组并制作列表。

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

Then you can put that in a dictionary or iterate it or something. 然后你可以把它放在字典中或迭代它或什么的。

Your dictionary code looks like it will function the way you expect. 您的dictionary代码看起来会像您期望的那样运行。

My best guess is that your string-splitting code is not working correctly. 我最好的猜测是你的字符串拆分代码无法正常工作。
You'd have to give us some sample inputs to verify this though. 你必须给我们一些样本输入来验证这一点。

Anyway, your entire block of code could be simplified and rewritten with LINQ as: 无论如何,您的整个代码块可以简化并使用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