Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do an inline sort?

Tags:

c#

linq

I would like to take a list, re-order it and replace the original.

Is there a better way to do this? Currently I am re-assigning it and it feels silly...

Here is my code:

var viewModel = new ViewModel();
viewModel.Children = viewModel.Children.OrderBy(x => x.Name).ToList();
like image 506
shenku Avatar asked Mar 19 '13 08:03

shenku


2 Answers

It seems you are looking for the List<T>.Sort method.

viewModel.Children.Sort((a, b) => string.Compare(a.Name, b.Name));
like image 67
Darin Dimitrov Avatar answered Sep 20 '22 14:09

Darin Dimitrov


Try to use List<T>.Sort method instead of.

Sorts the elements in the entire List<T> using the specified System.Comparison<T>.

viewModel.Children.Sort((a, b) => String.Compare(a.Name, b.Name))
like image 37
Soner Gönül Avatar answered Sep 22 '22 14:09

Soner Gönül