亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

動態 Linq Core OrderBy 可空子屬性

動態 Linq Core OrderBy 可空子屬性

C#
慕桂英546537 2022-07-23 17:43:09
當我嘗試使用System.Linq.Dynamic.Core庫來訂購列表時,我得到一個NullReferenceException.var myFinalOrderedList = myList.AsQueryable()    .OrderBy("Company.Name asc, Process.Name asc, Reference.Name asc")    .ToList();Reference.Name OrderBy因為是可以為空的,所以發生了空異常Reference。如何按可空Reference對象排序?StackTrace(敏感信息替換為“****”):    {  "ClassName": "System.NullReferenceException",  "Message": "Object reference not set to an instance of an object.",  "Data": null,  "InnerException": null,  "HelpURL": null,  "RemoteStackTraceString": null,  "RemoteStackIndex": 0,  "ExceptionMethod": null,  "HResult": -2147467261,  "Source": "Anonymously Hosted DynamicMethods Assembly",  "WatsonBuckets": null}Company、Process 和 Reference 是主列表 (ControlActivity) 的外鍵。這三個幾乎都只有 PK Id 和 NVARCHAR 名稱。所有控制活動都需要公司和流程,并且不需要參考。
查看完整描述

1 回答

?
白豬掌柜的

TA貢獻1893條經驗 獲得超10個贊

在@Alen 和https://github.com/StefH/System.Linq.Dynamic.Core/issues/98發布的鏈接的幫助下,我找到了自己問題的答案。下面,我將展示更多我的實際代碼,這就是它看起來與問題不同的原因。答案在于StaticMethod.ConvertToNullableNested. 例如,我正在傳遞,{i.ColumnName} {i.SortOrder} = "Company.Name asc"它正在返回Company == null ? null : Company.Name asc。然后我將每個排序附加在一起并傳遞給 OrderBy。


//TURN INTO QUERYABLE

var finalList = unionList.AsQueryable();


//DYNAMIC SORT

if (input.SortModel?.SortModelItems?.Count > 0)

{

    string sortQry = String.Empty;

    foreach (var i in input.SortModel.SortModelItems)

    {

        sortQry = sortQry + $"{StaticMethod.ConvertToNullableNested($"{i.ColumnName} {i.SortOrder}")}, ";

    }

    sortQry = sortQry.TrimEnd(", ");

    finalList = finalList.OrderBy(sortQry);

}


//RETURN AND REMEMBER TO .TAKE(Pagesize)

return Tuple.Create(finalList.Take(input.PageSize).ToList(), finalRowCount);

public static string ConvertToNullableNested(string expression, string result = "", int index = 0)

    {

        //Transforms => "a.b.c" to "(a != null ? (a.b != null ? a.b.c : null) : null)"

        if (string.IsNullOrEmpty(expression))

            return null;

        if (string.IsNullOrEmpty(result))

            result = expression;

        var properties = expression.Split(".");

        if (properties.Length == 0 || properties.Length - 1 == index)

            return result;

        var property = string.Join(".", properties.Take(index + 1));

        if (string.IsNullOrEmpty(property))

            return result;

        result = result.Replace(expression, $"{property} == null ? null : {expression}");

        return ConvertToNullableNested(expression, result, index + 1);

    }


查看完整回答
反對 回復 2022-07-23
  • 1 回答
  • 0 關注
  • 207 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號