Search code examples
c#listribboncpu-word

how to order List<T> through string child element?


I must order a list according to a string contained in each element of the list.

I have a ribbonDropDown element which contains a list of ribbonDropDownItem. Each of those item contains a string from which I want to reorder the item position in the ribbonDropDown alphabatically. I think my problem can be solve just by considering I have a List of object which contain a string field.

I tried this :

List<myObject> myList = aList;
myList.OrderBy(i => i.Name, StringComparer.Ordinal);

and also

myList.OrderBy(i => i.Name);

I expect the result to be order from a->z or z->a depending on the method I use (OrderBy or OrderBy descening). For now my result is the same order of my list before the operation.

Is it possible to use this method for that or should I use something else ? I'd like not to use a for loop.


Solution

  • You need to reassign the return of the .OrderBy() to the original list.

    myList = myList.OrderBy(i => i.Name).ToList();
    

    .OrderBy() does not change the existing list, it returns the input list with the modifications as a new IEnumerable<>.