I am having a hard time creating working Group By and Sort By clauses against a generic List myList.
myList has a list of property ‘Settings’ which itself contains a list of ‘child’ properties for each business.
I want to group by a Industry and within each Industry, sort by business name. My intent would be this:
string groupSetting = "Industry";
sortSetting = "BusinessName";
myList.GroupBy(p => p.Settings.Find(s => s.Name == groupSetting)).OrderBy(p => p.Settings.Find(t => t.Name == sortSetting));
However I am getting the error :
‘System.Linq.IGrouping does not contain a definition for Settings and no extension method Settings accepting a first argument of type System.Linq.Igrouping could be found….‘ indicating I cannot invoke the order by clause without some transformation or additional treatment.
I have tried all sorts of things to split this out and get it working, but I am missing something. Any help appreciated
Your problem is that
GroupBydoesn’t return a single list of settings, it returns a “list-of-lists”. This is theIGroupingwhich you are seeing.You need to iterate over each group in the
IGrouping, sort that group, and then iterate over each item within the group. Observe:Data structures provided for clarity:
This produces the following output: Copy/paste the code and run it and play with it