23

Any idea why the LINQ OrderBy is not working in following code, (have no errors but method does not sort ...)

First my own type

public class IQLinksView
    {
        public int id { get; set; }
        public int catid { get; set; }
        public int? viewed {get;set;}
        public string name {get;set;}
        public string desc {get;set;}
        public string url {get;set;}
        public string pic {get;set;}
        public string cat {get;set;}
    }

then query :

IQueryable<IQLinksView> newView = 
              from links in this.emContext.tbl_otherlinks
              select new IQLinksView { id = links.pklinkid, catid =
              links.tbl_catgeory.pkcategoryid, viewed = links.linkviewed, name = links.linkname, 
              desc = links.linkdesc, pic = links.linkpicture,   url = links.linkurl, cat =
              links.tbl_catgeory.categoryname };

Untill here all fine :-), but then

newView.OrderBy(x => x.viewed);

just changes nothing,... Page is loading results showing ... but no ordering ... sniff

i have Try with (creating a comparer object ... ):

newView.OrderBy(x => (Int32)x.viewed, new CompareIntegers());

same result, no ordering ...

I do have workarounds but just wondering what is missing ....

Any suggestions will be appreciated thanks a lot :-)

2 Answers 2

56

Don't throw away the return value. The OrderBy extension method is does not mutate the input. Try:

newView = newView.OrderBy(x => x.viewed);

There is no reason why that won't work, assuming the viewed value is correct. Also, make sure that OrderBy is after any operations (e.g. Distinct) which will ruin ordering.

Happy coding!

3
  • 1
    Super ! Works fine, did not think of the return, assumed mutation May 24, 2012 at 19:31
  • My problem was I had it before a distinct. Oct 22, 2015 at 15:42
  • I was ordering by a field that wasn't being displayed Jun 17, 2016 at 16:34
0

No-Tracking Queries

Consider use the asnotracking() after orderby() if the result is a readonly result.

Example:

query = query.OrderByDescending(x => x.Rating).AsNoTracking();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.