c# - 构建列表中项目计数的字典

标签 c# list dictionary

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

例子:

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<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<string, int> 是一个很短的跳跃:

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

关于c# - 构建列表中项目计数的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/687313/

相关文章:

c# - 手电筒应用程序每次在 Windows Phone 中崩溃

c# - "Set as Startup"在 C# winforms 解决方案中定义和保存在哪里?

python - 没有项目从列表中删除

c# - 数据结构Memory Mapped还是DB? (百万件)

Python - 在 csv 文件中显示具有重复值的行

c# - c++ std::map::find 到 c# dictionary<key,value>

c# - 以编程方式在运行时更改 NLog 目标中的 basedir

c# - SpreadsheetML 到 Open XML (XLSX) 的 Excel 转换

python-3.x - Python 对象引用解决方法

c# - 如何通过用户输入(控制台应用程序)使用 C# 中的列表使用 IndexOf 方法自动递增 int userid?