Linq Query Group By and Selecting First Items

后端 未结 4 403
余生分开走
余生分开走 2020-11-29 02:59

I have a String array kinda like this:

// icon, category, tool
String[,] subButtonData = new String[,]
{
    {\"graphics/gui/brushsizeplus_icon\", \"Draw\",          


        
4条回答
  •  爱一瞬间的悲伤
    2020-11-29 04:01

    var results = list.GroupBy(x => x.Category)
                .Select(g => g.OrderBy(x => x.SortByProp).FirstOrDefault());
    

    For those wondering how to do this for groups that are not necessarily sorted correctly, here's an expansion of this answer that uses method syntax to customize the sort order of each group and hence get the desired record from each.

    Note: If you're using LINQ-to-Entities you will get a runtime exception if you use First() instead of FirstOrDefault() here as the former can only be used as a final query operation.

提交回复
热议问题