How can I make my order work with an anonymous type?

What do I put in my order? I want to order by name. I moved orderby after the individual because I read that this should be done last.

var result = (from r in db.RecordDocs where r.RecordID == recordID select new { DocTypeID = r.Document.DocType.DocTypeID, Name = r.Document.DocType.Name, Number = r.Document.DocType.Number } ).Distinct().OrderBy( ); 
+6
linq
source share
2 answers

Just do

 .OrderBy(doc => doc.Name) 
+13
source share

Another option, if you really prefer the syntax of the query expression, would be to build a query chain for several statements:

 var query = from r in db.RecordDocs where r.RecordID == recordID select new { DocTypeID = r.Document.DocType.DocTypeID, Name = r.Document.DocType.Name, Number = r.Document.DocType.Number }; query = query.Disctinct(); query = from doc in query orderby doc.Name select doc; 

Since all of these methods are deferred, this will result in exactly the same execution performance.

+3
source share

All Articles