linq->SQL orderby descending not working

巧了我就是萌 提交于 2021-02-04 16:27:29

问题


var Customer = (from c in DNAContextSQL.Customers
                                where c.LastName != ""
                                orderby c.PKID_Customer descending
                                select new
                                {
                                    c.PKID_Customer,
                                    c.OrganizationName,
                                    c.FirstName,
                                    c.LastName,
                                    c.Phone,
                                    c.Extension
                                }).Distinct().ToList();

I know this is basic. I can't find any good reason why it's not working though. The queries sent to SQL Profiler don't seem to have an order by clause in them.

Any ideas?

I can get it to work with .OrderByDescending(...) but would like to know the reason behind this madness.


回答1:


The distinct is probably messing up the order by try calling the orderBy after the distinct()

var Customer = (from c in DNAContextSQL.Customers
                where c.LastName != ""
                select new
                   {
                      c.PKID_Customer,
                      c.OrganizationName,
                      c.FirstName,
                      c.LastName,
                      c.Phone,
                      c.Extension
                    }
                ).Distinct().OrderByDescending(c=>c.PKID_Customer).ToList();

This is happening because you first select a set of rows that are ordered by the PKID_Customer (and they are ordered until you call the distinct() method), and after that the Distinct() method rearranges them into a new distinct unordered set of records.



来源:https://stackoverflow.com/questions/6431319/linq-sql-orderby-descending-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!