Sort a Collection of Integers

I have a collection {8,3,2,4,0,5} of integers.
I’m trying to order them from smallest to greatest
And also from greatest to smallest.

I’m attempting to use linq to sort it.

I tried OrderBy and OrderByDescending, but I can’t
Think of what to put in the argument to make it order the numbers. Any ideas?

 Collection  =  {8,3,2,4,0,5}
 orderedCollection = Collection.OrderBy(Function(x) 'order min to max) 
  
      For Each Item in orderedCollection{ print item } 

That’s the Pseudo-code for what I’m basically trying to do.

I want it to print
0 2 3 4 5 8

And the other way also
8 5 4 3 2 0

1 Like

The easiest way is to use a sortable datatype for this like
SortedList, SortedSet, SortedDictionary, …

Read this for example:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedlist-2?redirectedfrom=MSDN&view=netframework-4.7.2

regards
Markus

1 Like

Hi Heather,

To do that with OrderBy or OrderByDescending you just need to put the argument as the expressions to order by. Something like collection.OrderBy(Function(x) x). This works because x is a primitive data type.

For a complex data type, you can specified the property to use for the sorting, like collection.OrderBy(Function(x) x.Somefieldtoorderby.

Regards
Silviu

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.