LINQ order issue

I pass from the controller an array generated by the following code:

public ActionResult GetClasses(bool ajax, string kingdom)
        {
            int _kingdom = _taxon.getKingdom(kingdom);

            var query = (from c in vwAnimalsTaxon.All()
                         orderby c.ClaName
                         select new { taxRecID = c.ClaRecID, taxName = c.ClaName }).Distinct();

            return Json(query, JsonRequestBehavior.AllowGet);
        }

A list of queries should be ordered, but it doesn’t work, I get the names of classes that are ordered incorrectly in the array, because I saw how it debugs that the names are not ordered. The view is just a dropdownbox loading automatically, so I'm pretty sure the problem is with the action. Do you see something wrong? Did I miss something?

+3
source share
4 answers

, gmcalab . , , , Distinct . , THEN OrderBy. , :

var query = (from c in vwAnimalsTaxon.All()
    select new { taxRecID = c.ClaRecID, taxName = c.ClaName }
).Distinct().OrderBy(t => t.taxName); 
+10

:

var query = (from c in vwAnimalsTaxon.All()
             select new { taxRecID = c.ClaRecID, taxName = c.ClaName }
).Distinct().OrdeyBy(c => c.ClaName);
+2

In LINQ, the Distinct method makes no guarantees regarding the order of the results. In many cases, Distinct causes the OrderBy method to be optimized. Therefore, you must make OrderBy the last one after Distinct.

var query = (from c in vwAnimalsTaxon.All()
             select new { taxRecID = c.ClaRecID, taxName = c.ClaName })
            .Distinct()
            .OrderBy(c => c.ClaName);
+1
source

The selection will also remove the sort. Thus, either Distinct or Select requires orderby after.

0
source

Source: https://habr.com/ru/post/1739998/


All Articles