Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of items using OrderBy<>

Tags:

I have an array of items and I would like to sort on one of their properties. I can access the items property using "item.Fields["FieldName"].Value" the property is returned as a string but I can cast it to an int.

I had a look at OrderBy<> but I have no idea of how to use it.

like image 480
Zooking Avatar asked Mar 06 '09 21:03

Zooking


People also ask

How do you sort an array of objects?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.

How do you sort an array in C#?

The simplest way to sort an array in C# is using Array. Sort method. The Array. Sort method takes a one-dimensional array as an input and sorts the array elements in the ascending order.

Can you use sort () on an array?

Just like numeric arrays, you can also sort string array using the sort function. When you pass the string array, the array is sorted in ascending alphabetical order.


1 Answers

To be clear, OrderBy won't sort the array in place - it will return a new sequence which is a sorted copy of the array. If that's okay, then you want something like:

var sorted = array.OrderBy(item => item.Fields["FieldName"].Value); 

On the other hand, I don't understand your comment that the property is returned as a string but that you can cast it to an int - you can't cast strings to ints, you have to parse them. If that's what you meant, you probably want:

var sorted = array.OrderBy(item => int.Parse(item.Fields["FieldName"].Value)); 

If you want that as an array, you can call ToArray() afterwards:

var sorted = array.OrderBy(item => int.Parse(item.Fields["FieldName"].Value))                   .ToArray(); 

Alternatively you could use Array.Sort if you want to sort in-place, but that will be somewhat messier.

like image 90
Jon Skeet Avatar answered Oct 06 '22 10:10

Jon Skeet