tags:

views:

47

answers:

2
+1  Q: 

LINQ OrderBy query

Hello all.

I have the following that pulls through a list of suppliers:

public List<tblSupplierPerformance> GetSupplierInfo(string memberid, string locationid, string supplieridname)
{
    MyEntities suppliers = new MyEntities();

    var r = (from p in suppliers.tblSupplierPerformances
             where p.MemberId == memberid && p.LocationId == locationid
             orderby p.TotalPurchaseQuantity 
             select p)
            .Distinct();

    if (supplieridname != "0")
        r = r.Where(p => p.SupplierIDName == supplieridname);

    return r.ToList();
}

However, when this runs, the orderby doesn't seem to be ordering.

I think, think, I need to implement the orderby at the "return r." stage, but I don't really know how to do this or I could be very much wrong all over the shop!

Any pointers gladly received.

+4  A: 

I suspect it's the Distinct call which is messing up the ordering... although as you're not joining or doing anything like that, I'm not sure why you need distinct - isn't each entity naturally distinct?

Anyway, you could certainly move the ordering to the return statement:

return r.OrderBy(p => p.TotalPurchaseQuantity).ToList();
Jon Skeet
Good point about the distinct - now legacy : )
Ricardo Deano
Just for anyone who is looking for something simialr, I did the above but with OrderByDescending which, funnily enough, ordered the totalpurchaseQuantity descending.Thanks Jon.
Ricardo Deano
+1  A: 

yes u need to implement order by in the return

return r.ToList().OrderBy(o => o.Column1);
anishmarokey
That will perform the sorting in .NET itself rather than at the database, which is likely to be less efficient. Putting it *before* the call to `ToList` does it in SQL.
Jon Skeet
@Jon thank a lot for your valuable comment.Good point !!!!
anishmarokey