Rya*_*che 9 c# dictionary list
我有一个包含一堆可以多次出现的字符串的List.我想获取此列表并构建列表项的字典作为键和它们的出现次数作为值.
例:
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;
}
cas*_*One 24
您可以使用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<string, int>:
var dictionary = groups.ToDictionary(g => g.Stuff, g => g.Count);
我会创建一个专门的List,由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 );
   }
}
| 归档时间: | 
 | 
| 查看次数: | 9440 次 | 
| 最近记录: |