NealR
NealR

Reputation: 10709

Linq query no longer ordered properly after .Distinct() used

Below is a simple Linq query I am using to fill in a jquery autocomplete list. The list is ordered properly until after the .Distinct() method gets called. Can anyone clue me in as to why or a way to remove duplicates from the list and keep it in order?

    public JsonResult OverrideSearch(string term)
    {
        var drm = from    d in db.ZipCodeTerritory
                  where   d.DrmTerrDesc.Contains(term)
                  orderby d.DrmTerrDesc
                  select  d.DrmTerrDesc;

        drm = drm.Distinct();

        return Json(drm, JsonRequestBehavior.AllowGet);
    }

Upvotes: 1

Views: 65

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236278

Apply ordering after distinct:

public JsonResult OverrideSearch(string term)
{
    var drm = db.ZipCodeTerritory
                .Where(d => d.DrmTerrDesc.Contains(term))
                .Select(d => d.DrmTerrDesc)
                .Distinct()
                .OrderBy(d => d);

    return Json(drm, JsonRequestBehavior.AllowGet);
}

Or with query syntax (I don't like to mix query and method syntax):

public JsonResult OverrideSearch(string term)
{
    var drm = from d in db.ZipCodeTerritory
              where d.DrmTerrDesc.Contains(term)
              select  d.DrmTerrDesc;

    drm = drm.Distinct();

    return Json(drm.OrderBy(d => d), JsonRequestBehavior.AllowGet);
}

BTW there is a remark on Queryable.Distinct method at MSDN which tells that it usually returns unordered sequence:

The query behavior that occurs as a result of executing an expression tree that represents calling Distinct(IQueryable) depends on the implementation of the type of the source parameter. The expected behavior is that it returns an unordered sequence of the unique items in source.

Upvotes: 2

Related Questions