LINQ的排序依据。如果没有语句中工作 [英] Linq OrderBy not Working within If statement

查看:130
本文介绍了LINQ的排序依据。如果没有语句中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有问题,有没有对任何种类影响排序依据条款。我已经通过此在调试器走和投保这是code的排序行被击中并的情况下审查后它由没有被应用的顺序。结果

 公共静态的IEnumerable< D​​DLOptions< TValueType>> GetDDLOptionsViewModel< TClass,TValueType>(
            IEnumerable的< TClass>列表中,
            FUNC< TClass,TValueType>值,
            FUNC< TClass,串> displayText,
            布尔排序= TRUE
        )
        {
            清单< D​​DLOptions< TValueType>> ddlOptions;            ddlOptions = list.Select(
                L =>新DDLOptions< TValueType>
                        {
                            值=值(L),
                            DisplayText = displayText(升)
                        }
                    ).ToList(); < ==========工作,如果我把这个顺序按这里。            如果(排序)
            {
                ddlOptions.OrderBy(L => l.DisplayText); < =====这里不起作用。
            }            返回ddlOptions;
        }


解决方案

排序依据返回的,将执行排序的查询:它不修改原始列表(而像列表< T>的.sort 将修改原)

相反,尝试这样的:

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

编辑:您可能希望与 ddlOptions 的类型或者/你如何返回数据,因为我们正在做一个额外的打左右了ToList 可能比必要的,但是这可能是一个小/非问题对于这种情况呢。

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 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.

这篇关于LINQ的排序依据。如果没有语句中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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