[英]using Ternary operator/conditional on select on dynamic linq
I am looking to do a linq queyr with Dynamic linq library but I am trying to select a property which is a IEnumerable collection which throws an exception with Calling the Sum() function, within Dynamic linq so I am wondering if I could say something like我想用动态 linq 库做一个 linq 查询,但我正在尝试 select 一个属性,它是一个 IEnumerable 集合,它在动态 linq 中调用 Sum() function 时抛出异常所以我想知道我是否可以说类似的话
queryable.Select("new ( Sum(collection ==null ? 0:collection.Count) as Total )")
because因为
Select("new ( Sum(np(Contestants.Count,0)) as Total )")
returns a null reference exception返回 null 引用异常
The np
(NullPropagation) is used correctly, but Sum
can only be used if you group. np
(NullPropagation) 使用正确,但Sum
只能在分组时使用。 (Just like normal Linq) (就像普通的 Linq)
A possible working code example could be:一个可能的工作代码示例可能是:
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.