How can I do inline sorting?

I would like to take a list, reorder it and replace the original.

Is there a better way to do this? I am currently reassigning him and he is feeling stupid ...

Here is my code:

var viewModel = new ViewModel(); viewModel.Children = viewModel.Children.OrderBy(x => x.Name).ToList(); 
+4
source share
3 answers

You seem to be looking for a List<T>.Sort .

 viewModel.Children.Sort((a, b) => string.Compare(a.Name, b.Name)); 
+13
source

Try using List<T>.Sort instead.

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

 viewModel.Children.Sort((a, b) => String.Compare(a.Name, b.Name)) 
+1
source

Try using lambda expressions :

 viewModel.Children.Sort((a, b) => String.Compare(a.Name, b.Name)) 

For IList, this will not work:

 viewModel.Children = viewModel.Children.OrderBy(x => x.Name).ToList(); 
0
source

All Articles