简体   繁体   中英

How to use linq orderby with a group by

I have a query below and I will like to orderby t.day. I am new to linq. Where do I put the orderby t.day in this query below? Thanks.

        var pracResult = (from t in queryResult
                            group t by new {t.RouteNbr, t.Day,t.NumberOfActionPlans,t.RouteNbrPlusDay}
                            into grp                                     
                            select new
                            {
                                grp.Key.RouteNbr,
                                grp.Key.Day,
                                grp.Key.NumberOfActionPlans,
                                grp.Key.RouteNbrPlusDay,
                            }).ToList();


        //orderby t.Day

I did not understand why you again converted your groups to their keys. If you intend to order your groups you can use,

var pracResult = (from t in queryResult
                        group t by new {t.RouteNbr,  t.Day,t.NumberOfActionPlans,t.RouteNbrPlusDay}
                        into grp 
                        orderby grp.Key.Day                                    
                        ).ToList();

Else if you want exact equivalent of your code why not just doing this,

var pracResult = queryResult.Select(i => new {i.RouteNbr, i.Day, i.NumberOfActionPlans, i.RouteNbrPlusDay})
                        .Distinct() 
                        .OrderBy(k => k.Day)
                        .ToList();

You can add

orderby krp.Key.Day

after the group clause.

Try this:

 var pracResult = queryResult.GroupBy(t => new {t.RouteNbr, t.Day,t.NumberOfActionPlans,t.RouteNbrPlusDay})
                             .OrderBy(l => l.Key.Day)
                             .Select(grp =>new{ grp.Key.RouteNbr,
                                                 grp.Key.Day,
                                                 grp.Key.NumberOfActionPlans,
                                                 grp.Key.RouteNbrPlusDay}).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM