Linq Query Group By and Selecting First Items

后端 未结 4 387
余生分开走
余生分开走 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 03:47
    var result = list.GroupBy(x => x.Category).Select(x => x.First())
    
    0 讨论(0)
  • 2020-11-29 03:49

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

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

    See an example in my post "Select First Row In Group using Custom Comparer"

    0 讨论(0)
  • 2020-11-29 03:54

    First of all, I wouldn't use a multi-dimensional array. Only ever seen bad things come of it.

    Set up your variable like this:

    IEnumerable<IEnumerable<string>> data = new[] {
        new[]{"...", "...", "..."},
        ... etc ...
    };
    

    Then you'd simply go:

    var firsts = data.Select(x => x.FirstOrDefault()).Where(x => x != null); 
    

    The Where makes sure it prunes any nulls if you have an empty list as an item inside.

    Alternatively you can implement it as:

    string[][] = new[] {
        new[]{"...","...","..."},
        new[]{"...","...","..."},
        ... etc ...
    };
    

    This could be used similarly to a [x,y] array but it's used like this: [x][y]

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题