Linq 查询分组依据和选择第一项 [英] Linq Query Group By and Selecting First Items
本文介绍了Linq 查询分组依据和选择第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的字符串数组:
I have a String array kinda like this:
// icon, category, tool
String[,] subButtonData = new String[,]
{
{"graphics/gui/brushsizeplus_icon", "Draw", "DrawBrushPlus"},
{"graphics/gui/brushsizeminus_icon", "Draw", "DrawBrushMinus"},
{"graphics/gui/freedraw_icon", "Draw", "DrawFree"},
{"graphics/gui/linedraw_icon", "Draw", "DrawLine"},
{"graphics/gui/rectangledraw_icon", "Draw", "DrawRectangle"},
{"graphics/gui/ellipsedraw_icon", "Draw", "DrawEllipse"},
{"graphics/gui/brushsizeplus_icon", "Brusher", "BrusherBrushPlus"},
{"graphics/gui/brushsizeminus_icon", "Brusher", "BrusherBrushMinus"},
{"graphics/gui/brushsizeplus_icon", "Text", "TextBrushPlus"},
{"graphics/gui/brushsizeminus_icon", "Text", "TextBrushMinus"},
};
然后我用名为 mainButtons
这是我查询Category
分组的方式:
This is how I query for grouping for Category
:
var categories = from b in mainButtons
group b by b.category into g
select new { Category = g.Key, Buttons = g };
如何选择主列表中每个组的第一项?(不迭代每个并添加到另一个列表?)
How can I select the first item of each group in my main List? (without iterating each and adding to another List?)
推荐答案
参见 LINQ:如何使用 group by 子句获取最新/最后一条记录
var firstItemsInGroup = from b in mainButtons
group b by b.category into g
select g.First();
我假设 mainButtons 已经正确排序.
I assume that mainButtons are already sorted correctly.
如果您需要指定自定义排序顺序,请使用带有比较器的 OrderBy 覆盖.
If you need to specify custom sort order, use OrderBy override with Comparer.
var firstsByCompareInGroups = from p in rows
group p by p.ID into grp
select grp.OrderBy(a => a, new CompareRows()).First();
在我的帖子中看到一个例子 使用自定义比较器选择组中的第一行"
See an example in my post "Select First Row In Group using Custom Comparer"
这篇关于Linq 查询分组依据和选择第一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文