簡體   English   中英

在動態 linq 上使用三元運算符/條件 select

[英]using Ternary operator/conditional on select on dynamic linq

我想用動態 linq 庫做一個 linq 查詢,但我正在嘗試 select 一個屬性,它是一個 IEnumerable 集合,它在動態 linq 中調用 Sum() function 時拋出異常所以我想知道我是否可以說類似的話

queryable.Select("new ( Sum(collection ==null ? 0:collection.Count) as Total )")

因為

Select("new ( Sum(np(Contestants.Count,0)) as Total )")

返回 null 引用異常

np (NullPropagation) 使用正確,但Sum只能在分組時使用。 (就像普通的 Linq)

一個可能的工作代碼示例可能是:

public class X
{
    public string Key { get; set; } = null!;

    public List<Y>? Contestants { get; set; }
}

public class Y
{
}
var q = new[]
{
    new X { Key = "x" },
    new X { Key = "a" },
    new X { Key = "a", Contestants = new List<Y> { new Y() } }
}.AsQueryable();
var groupByKey = q.GroupBy("Key");
var selectQry = groupByKey.Select("new (Key, Sum(np(Contestants.Count, 0)) As TotalCount)").ToDynamicList();

調試結果: 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM