我有一个类似于以下内容的字符串数组:

// 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的按钮类型填充List<Button>

我是这样查询Category的分组的:

var categories = from b in mainButtons
                 group b by b.category into g
                 select new { Category = g.Key, Buttons = g };

如何在主列表中 Select 每组的第一项?(没有迭代每个列表并添加到另一个列表?)

推荐答案

LINQ: How to get the latest/last record with a group by clause

var firstItemsInGroup = from b in mainButtons
                 group b by b.category into g
select g.First();

我假设主按钮已经正确排序.

如果需要指定自定义排序顺序,请将OrderBy重写与比较器一起使用.

var firstsByCompareInGroups = from p in rows
        group p by p.ID into grp
        select grp.OrderBy(a => a, new CompareRows()).First();

参见我的"Select First Row In Group using Custom Comparer篇博文中的一个例子"

.net相关问答推荐

Docker失败文件找不到

为什么.Net 8.0.100是预览版?

SeriLog LogConext.PushProperty在ASP.NET MVC 5中不能使用OWIN中间件

Blazor服务器应用程序需要在页面上点击才能与元素交互

无法在 Blazor Server 应用程序中触发 InputRadio 的 onchange 事件

在 Invoke() 中运行时,跨线程操作对表单控件无效 - .NET

cmd 冻结中的 dotnet 命令.怎么了?

在c#中计算中位数

如何摆脱 VS2008 中的目标程序集不包含服务类型错误消息?

每第 N 个字符/数字拆分一个字符串/数字?

有没有办法以编程方式最小化窗口

我可以使用 UriTemplate 将非字符串传递给 WCF RESTful 服务吗?

为什么需要 XmlNamespaceManager?

静态析构函数

我们应该总是在类中包含一个默认构造函数吗?

在 .NET 中填充整数列表

在 .NET 中计算目录大小的最佳方法是什么?

在 Windows 窗体 C# 应用程序中拥有配置文件的最简单方法

WPF 中的 Application.DoEvents() 在哪里?

Roslyn 编译代码失败