您可以使用"分组依据"+"orderby".有关详细信息,请参见LINQ 101
var list = new List{"a", "b", "a", "c", "a", "b"}; var q = from x in list group x by x into g let count = g.Count() orderby count descending select new {Value = g.Key, Count = count}; foreach (var x in q) { Console.WriteLine("Value: " + x.Value + " Count: " + x.Count); }
回复这篇文章(现已删除):
如果您有一些自定义对象的列表,则需要使用自定义比较器或按特定属性分组.
查询也无法显示结果.向我们展示完整的代码以获得更好的帮助.
根据您的最新更新:
你有这行代码:
group xx by xx into g
由于xx是自定义对象系统,因此不知道如何将一个项目与另一个项目进行比较.正如我已经写过的,您需要引导编译器并提供一些将在对象比较中使用的属性或提供自定义比较器.这是一个例子:
请注意,我使用Foo.Name作为键 - 即对象将根据Name属性的值进行分组.
有一个问题 - 您根据名称对待2个对象是重复的,但是Id呢?在我的例子中,我只是获取组中第一个对象的Id.如果您的对象具有不同的ID,则可能是个问题.
//Using extension methods var q = list.GroupBy(x => x.Name) .Select(x => new {Count = x.Count(), Name = x.Key, ID = x.First().ID}) .OrderByDescending(x => x.Count); //Using LINQ var q = from x in list group x by x.Name into g let count = g.Count() orderby count descending select new {Name = g.Key, Count = count, ID = g.First().ID}; foreach (var x in q) { Console.WriteLine("Count: " + x.Count + " Name: " + x.Name + " ID: " + x.ID); }
使用方法链的版本略短:
var list = new List{"a", "b", "a", "c", "a", "b"}; var q = list.GroupBy(x => x) .Select(g => new {Value = g.Key, Count = g.Count()}) .OrderByDescending(x=>x.Count); foreach (var x in q) { Console.WriteLine("Value: " + x.Value + " Count: " + x.Count); }
你也可以做词典:
var list = new List{ "a", "b", "a", "c", "a", "b" }; var result = list.GroupBy(x => x) .ToDictionary(y=>y.Key, y=>y.Count()) .OrderByDescending(z => z.Value); foreach (var x in result) { Console.WriteLine("Value: " + x.Key + " Count: " + x.Value); }
其他解决方案使用GroupBy
。GroupBy
速度很慢(它将所有元素保存在内存中),所以我写了自己的方法CountBy
:
public static DictionaryCountBy (this IEnumerable source, Func keySelector) { var countsByKey = new Dictionary (); foreach(var x in source) { var key = keySelector(x); if (!countsByKey.ContainsKey(key)) countsByKey[key] = 0; countsByKey[key] += 1; } return countsByKey; }