问题
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