clamchoda
clamchoda

Reputation: 4951

Linq Sorted Groupby and Orderby fields

I feel I am just on the edge of my answer!

I have a custom fileInfo class with holders info such as "reporting store number" , "report date" etc...

I have a List<fileInfo> which I hold all file information. I have attempted to group the list by "reporting store number" and order by "report date"

I have come up with the following

var results = ownedFileInfo.GroupBy(x => x.reportStore).Select(group=> new { KeyName = group.Key, KeyInfo =  group.OrderBy(x=>x.reportDate).ThenBy(x=>x.reportStore)});

List<fileInfo> sortedFiles = new List<fileInfo>();
                    foreach (var group in results)
                    {

                        foreach (fileInfo fi in group.KeyInfo)
                        {
                            sortedFiles.Add(fi);

                        }
                    }

The groupby and orderby functionality are working as expected. Although I was hoping the ThenBy would sort the groupby column as well :(

Results:

Expected results:

Could one of the more experience with linq please point out what I am missing or whats going wrong? Thank you in advanced for your time.

Upvotes: 1

Views: 244

Answers (2)

Andrey Shchekin
Andrey Shchekin

Reputation: 21599

I do not think for that output you need grouping at all:

var sortedFiles = ownedFileInfo.OrderBy(x => x.reportStore)
                               .ThenBy(x => x.reportDate)
                               .ToList();

Upvotes: 2

I4V
I4V

Reputation: 35353

I think what you need is

ownedFileInfo.GroupBy(x => x.reportStore).OrderBy(x=>x.Key).Select....

instead of

ownedFileInfo.GroupBy(x => x.reportStore).Select....

Upvotes: 1

Related Questions