LINQ:顺序按在册及LT独特的项目数;串> [英] LINQ: Order By Count of Unique Items in List<string>

查看:170
本文介绍了LINQ:顺序按在册及LT独特的项目数;串>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有ID列表妥善保存在一个List<>。我现在需要这个组列表,并获得出现的次数降序排序。

的计数

例如:

 列表<串GT; aryIDs =新的List<字符串取代;
aryIDs.Add(1234);
aryIDs.Add(4321);
aryIDs.Add(3214);
aryIDs.Add(1234);
aryIDs.Add(4321);
aryIDs.Add(1234);

会产生:

 1234,3
4321,2
3214,1

这会很容易在TSQL的,但我想,以避免服务器往返,不必要的表格等如果可能的话。

先谢谢了。

更新:VB.NET转换为以下拉尔夫希林的回答是:

 昏暗的结果=从ID在aryIDs _
                     组ID进行编号入组_
                     顺序按Group.Count()降序_
                     选择ID,计数= Group.Count()result.Dump()


解决方案

 列表<串GT; aryIDs =新的List<串GT;();
aryIDs.Add(1234);
aryIDs.Add(4321);
aryIDs.Add(3214);
aryIDs.Add(1234);
aryIDs.Add(4321);
aryIDs.Add(1234);VAR的结果=从ID在aryIDs
由ID为G组ID
排序依据g.Count()降
选择新的{ID = g.Key,计数= g.Count()};result.Dump();

剪切并粘贴到LinqPad,你应该是好去。

它也可以使用lambda前pressions书面:

  aryIDs.GroupBy(ID => ID).OrderByDescending(ID => id.Count())。选择(G =>新建{ID = g.Key,计数= g.Count()})转储();

I have a list of ids properly stored in a List<>. I now need to Group this list and get a count of the number of occurrences sorted descending.

Example:

List<string> aryIDs = new List<string>;
aryIDs.Add("1234");
aryIDs.Add("4321");
aryIDs.Add("3214");
aryIDs.Add("1234");
aryIDs.Add("4321");
aryIDs.Add("1234");

Would Produce:

"1234", 3
"4321", 2
"3214", 1

This would be easy in TSQL, but I would like to avoid the server roundtrip, unnecessary tables, etc. if possible.

Thanks in advance.

Update: The VB.NET conversion for Ralph Shillington's answer below:

Dim result = From id In aryIDs _
                     Group id By id Into Group _
                     Order By Group.Count() Descending _
                     Select id, Count = Group.Count()

result.Dump()

解决方案

List<string> aryIDs = new List<string>();
aryIDs.Add("1234");
aryIDs.Add("4321");
aryIDs.Add("3214");
aryIDs.Add("1234");
aryIDs.Add("4321");
aryIDs.Add("1234"); 

var result =     from id in aryIDs
group id by id into g
orderby g.Count() descending
select new { Id=g.Key, Count=g.Count() };

result.Dump();

Cut and paste that into LinqPad and you should be good to go.

It could also be written using Lambda expressions as:

aryIDs.GroupBy (id => id).OrderByDescending (id => id.Count()).Select(g => new { Id=g.Key, Count=g.Count()}).Dump();

这篇关于LINQ:顺序按在册及LT独特的项目数;串&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆