views:

89

answers:

3

Hi, I'm passing from the controller an array generated by the next 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);
        }

The query List should be ordered, but it doesn't work, I get the names of the classes ordered wrong in the array, because I've seen it debugging that the names are not ordered.The view is just a dropdownbox loaded automatically, so I'm almost sure the problem is with the action. Do you see anything wrong?Am I missing something?

+2  A: 

Give this a try:

var query = (from c in vwAnimalsTaxon.All()
             select new { taxRecID = c.ClaRecID, taxName = c.ClaName }
).Distinct().OrdeyBy(c => c.ClaName);
gmcalab
thank you, it works, although it should be c => t.taxName instead of c.ClaName in the orderBy method :D
vikitor
+7  A: 

I think gmcalab is almost there. The reason it's not working is that Distinct blows away the ordering. So you need Distinct THEN OrderBy. But this means you have to sort by the new attribute name:

var query = (from c in vwAnimalsTaxon.All()
    select new { taxRecID = c.ClaRecID, taxName = c.ClaName }
).Distinct().OrderBy(t => t.taxName); 
grossvogel
Yes, this is it, I didn't know this could happen that way, although I suspected something, but I didn't know how to do the orderby as a method...Thank you
vikitor
+1  A: 

In LINQ the Distinct method makes no guarantees about the order of results. In many cases the Distinct causes the OrderBy method to get optimized away. So it's necessary to do the OrderBy last, after the Distinct.

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