Link to home
Start Free TrialLog in
Avatar of Basicfarmer
BasicfarmerFlag for United States of America

asked on

Sort a Linq query

Experts, I am trying to figure out how to order this query Descending. Please help...
        Dim query = From company In dt.AsEnumerable
                    Select company.Field(Of String)("Company")
                    Distinct

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Basicfarmer

ASKER

Thanks, i was doing that but after the select and it wouldn't work like that.
Hi Basicfarmer;

The Distinct method call returns an unordered collection and so if you attempted to do it before the Distinct call it would not work. You need to do the ordering after the call to Distinct as shown below.

Dim query = (From company In dt.AsEnumerable
             Select company.Field(Of String)("Company")
             Distinct).OrderByDescending(Function(c) c) 

Open in new window

Fernando, thanks for the comment.
Hi Basicfarmer;

Not a problem. My statement about ordering came from Microsoft documentation [here] and full statement below.

The Distinct(Of TSource)(IEnumerable(Of TSource)) method returns an unordered sequence that contains no duplicate values. It uses the default equality comparer, Default, to compare values.
@Fernando

That's for Distinct itself, though. If you're already dealing with an ordered collection, I doubt that Distinct is going to re-order the distinct result differently than the ordered source. I'd have to test it, though. If anything, what I am suggesting would be an implementation detail, and the most guaranteed way to ensure an ordered result would be to order after the Distinct, as you mentioned.