Something fails to sort the sheet with a complex object, I seem to be doing everything correctly, but the list is not sorted.

List.groupby(x=>x.name).orderby(x => x.key.count()).reverse().toarray() 

Tell me what the problem can be? Or how to debug code here? Never linq debugged.

Ps I wrote from the memory of the tablet, could be a little wrong in the names

    2 answers 2

    Something tells me that you sorted by the number of characters in the name. Try this:

     List.groupby(x=>x.name).orderby(x => x.Count()).Reverse().ToArray() 

    If you look at it, it turns out that a grouping creates a class that implements the IGrouping <TKey, TElement> interface extending IEnumerable <TElement>. Thus, if you want to access the key, you use x.Key, and you can iterate the sequence like this:

     foreach (var item in x){} 

    Thus, to count the elements of a group, you need to use x.Count () instead of x.Key.Count ().

      The GroupBy operation groups the elements of a sequence in accordance with the specified key selector function and returns IEnumerable<IGrouping<TKey, TElement>> .


      In your case, you refer to the key and sort it by the number of characters in it.

      orderby (x => x.key.count ())

      To sort by the number of items in a group, you must use

       OrderBy(x => x.Count()) 

      In order not to use Reverse you can immediately sort in reverse order, i.e. in descending order. LINQ has a method called OrderByDescending for this.