LINQ查询GROUP BY和选择第一项第一项、LINQ、GROUP、BY

2023-09-02 01:40:31 作者:一直在梦想路上

我有一个字符串数组有点像这样的:

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

Then I populate a List<Button> with my Button Type named mainButtons

这是我如何查询分组为类别

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.

如果你需要指定自定义排序顺序,请使用排序依据替代与比较器。

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();

见我的文章的例子"Select排在第一位组使用自定义比较

 
精彩推荐
图片推荐