tcode
tcode

Reputation: 5105

Linq to Entities Group By Order By Not Working

I have a query which I want to return a list of objects of type tblcours, like so

public IList<tblcours> GetAllLiveCoursesByUnitID(int id)
{
    Expression<Func<tblcours, bool>> predicate = x => x.tblCourseCategoryLinks.Any(cl => cl.tblUnitCategory.tblUnit.unitID == id);
    int headingId = 180;

    var distinctResult = from c in _UoW.tblcoursRepo.All
                             .Where(c => c.MainHeadingID != headingId)
                             .Where(predicate)
                             group c by c.MainHeadingID into uniqueIds
                             select uniqueIds.FirstOrDefault();

    return distinctResult.ToList();

}

What this query is doing, is getting a list of objects of type tblcours and then removing duplicate records with the same MainHeadingID. This works nicely, however, I also need to the returned data to be in alphabetical order, however, no matter what I try, I can't it to do so.

So far I have tried the following

distinctResult.OrderBy(c => c.CourseTitle);
return distinctResult.ToList();

But this never works, it just continues to return the list un-ordered.

Could someone please help me with this?

Thanks for your help.

Upvotes: 0

Views: 2644

Answers (2)

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

Try this:

distinctResult= distinctResult.OrderBy(c => c.CourseTitle);
return distinctResult.ToList();

because OrderBy is returning ordered enumerable as here is said. Order by is not modyfing collection.

I highly recommend using resharper, he will catch such things and warn you

Upvotes: 4

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

You need to use the return value of OrderBy:

return distinctResult.OrderBy(c => c.CourseTitle).ToList();

OrderBy doesn't order distinctResult in place. Instead, it returns a new enumerable that is ordered.

Upvotes: 2

Related Questions