【问题标题】:Building a dictionary of counts of items in a list构建列表中项目计数的字典
【发布时间】:2010-10-15 19:08:24
【问题描述】:

我有一个列表,其中包含可以多次出现的字符串。我想使用这个列表并构建一个列表项的字典作为键,并将它们的出现次数作为值。

例子:

List<string> stuff = new List<string>();
stuff.Add( "Peanut Butter" );
stuff.Add( "Jam" );
stuff.Add( "Food" );
stuff.Add( "Snacks" );
stuff.Add( "Philosophy" );
stuff.Add( "Peanut Butter" );
stuff.Add( "Jam" );
stuff.Add( "Food" );

结果将是一个包含以下内容的字典:

"Peanut Butter", 2
"Jam", 2
"Food", 2
"Snacks", 1
"Philosophy", 1

我有办法做到这一点,但我似乎没有利用 C# 3.0 中的好东西

public Dictionary<string, int> CountStuff( IList<string> stuffList )
{
    Dictionary<string, int> stuffCount = new Dictionary<string, int>();

    foreach (string stuff in stuffList) {
        //initialize or increment the count for this item
        if (stuffCount.ContainsKey( stuff )) {
            stuffCount[stuff]++;
        } else {
            stuffCount.Add( stuff, 1 );
        }
    }

    return stuffCount;
}

【问题讨论】:

    标签: c# list dictionary


    【解决方案1】:

    您可以使用 C# 中的 group 子句来执行此操作。

    List<string> stuff = new List<string>();
    ...
    
    var groups = 
        from s in stuff
        group s by s into g
        select new { 
            Stuff = g.Key, 
            Count = g.Count() 
        };
    

    如果需要,您也可以直接调用扩展方法:

    var groups = stuff
        .GroupBy(s => s)
        .Select(s => new { 
            Stuff = s.Key, 
            Count = s.Count() 
        });
    

    从这里可以将其放入Dictionary&lt;string, int&gt;

    var dictionary = groups.ToDictionary(g => g.Stuff, g => g.Count);
    

    【讨论】:

    • 如何在第一个示例中添加 orderby?
    • @zadam 你总是可以说groups = groups.OrderBy(g =&gt; g.Stuff);
    【解决方案2】:

    我会制作一个由 Dictionary 支持的专门列表,并且 add 方法将测试成员资格并在找到时增加计数。

    有点像:

    public class CountingList
    {
        Dictionary<string, int> countingList = new Dictionary<string, int>();
    
       void Add( string s )
       {
            if( countingList.ContainsKey( s ))
                 countingList[ s ] ++;
            else
                countingList.Add( s, 1 );
       }
    }
    

    【讨论】:

      【解决方案3】:

      一个想法是将字典的default value 设为零,这样您就不必对第一次出现的情况进行特殊处理。

      【讨论】:

      • 嗯,这只是将处理特殊情况的代码移动到一个单独的类中......
      【解决方案4】:

      嗯,真的没有比这更好的方法了。

      也许您可以编写一个 LINQ 查询,将字符串分组,然后计算每个组中有多少个字符串,但这不会像您已经拥有的那样有效。

      【讨论】:

        【解决方案5】:
        Dictionary<string, int> a = stuff.GroupBy(p => p).OrderByDescending(r=>r.Count()).ToDictionary(q => q.Key, q => q.Count());
        

        您可以 GroupBy 然后创建字典来计算每个组。正如performance test 所指出的,通常有比 Linq 更有效的方法。我认为您的代码更高效,而 Linq 解决方案更具可读性和美观性。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-03-09
          • 2020-04-17
          • 2011-03-30
          • 1970-01-01
          • 2021-07-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多