您可以使用C#中的group子句来执行此操作.
Liststuff = new List (); ... 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
:
var dictionary = groups.ToDictionary(g => g.Stuff, g => g.Count);
我会创建一个专门的List,由Dictionary支持,add方法将测试成员资格并增加计数(如果找到).
有点像:
public class CountingList { DictionarycountingList = new Dictionary (); void Add( string s ) { if( countingList.ContainsKey( s )) countingList[ s ] ++; else countingList.Add( s, 1 ); } }