Linq OrderBy does not sort a List<T>. How do I sort the list?

OrderBy returns a query that would perform the ordering: it does not modify the original list (whereas something like List<T>.Sort would modify the original)

Instead try something like:

ddlOptions = ddlOptions.OrderBy(l => l.DisplayText).ToList();

EDIT: You might want to play around with the type of ddlOptions or where/how you return the data as we're doing an extra ToList than probably necessary, but that's probably a minor/non-issue for this case anyway.


Try:

if (sort)
{
    ddlOptions = ddlOptions.OrderBy(l => l.DisplayText); <===== Should work now.
}

As others have said, you need to assign the result of OrderBy to something as it doesn't mutate the sequence it acts on. It's easiest to make ddlOptions an IEnumerable instead of a List, so that you can assign the result to that. The ToList call on the select is also not needed:

public static IEnumerable<DDLOptions<TValueType>> GetDDLOptionsViewModel<TClass, TValueType>(
        IEnumerable<TClass> list,
        Func<TClass, TValueType> value,
        Func<TClass, string> displayText,
        bool sort = true
    )
{
    IEnumerable<DDLOptions<TValueType>> ddlOptions;

    ddlOptions = list.Select(
        l => new DDLOptions<TValueType>
                {
                    Value = value(l),
                    DisplayText = displayText(l)
                }
            );

    if (sort)
    {
        ddlOptions = ddlOptions.OrderBy(l => l.DisplayText);
    }

    return ddlOptions;
}

Note that this version of the method will use deferred execution, and so won't actually perform the Select/OrderBy until the sequence is iterated. If you don't want to do that, you can add ToList on the return line.

Tags:

C#

Linq