Linq OrderBy不对List< T>进行排序.如何对列表进行排序? [英] Linq OrderBy does not sort a List<T>. How do I sort the list?

查看:200
本文介绍了Linq OrderBy不对List< T>进行排序.如何对列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OrderBy子句有问题,对排序没有任何影响.我已经在调试器中进行了遍历,并确保了这种情况是命中了代码的排序行,并在未应用排序依据之后检查结果.

Having issues with the OrderBy clause not having any impact on the sort. I have walked through this in the debugger and insuring this is a case that the sort line of the code is being hit and reviewing the results after it the order by has not been applied.

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

            ddlOptions = list.Select(
                l => new DDLOptions<TValueType>
                        {
                            Value = value(l),
                            DisplayText = displayText(l)
                        }
                    ).ToList();  <========== Works if I put the Order By here.

            if (sort)
            {
                ddlOptions.OrderBy(l => l.DisplayText); <===== Does NOT work here.
            }

            return ddlOptions;
        }

推荐答案

OrderBy 返回可以执行排序的查询:它不会修改原始列表(而类似List<T>.Sort会修改原始内容)

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();

您可能想尝试使用ddlOptions的类型,或者在我们执行可能超出必要的ToList时,在何处/如何返回数据,但这可能是次要的/没有问题的无论如何,这种情况.

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.

这篇关于Linq OrderBy不对List&lt; T&gt;进行排序.如何对列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆