Home > Blockchain >  using Ternary operator/conditional on select on dynamic linq
using Ternary operator/conditional on select on dynamic linq

Time:11-22

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

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

CodePudding user response:

The np (NullPropagation) is used correctly, but Sum can only be used if you group. (Just like normal 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();

Debug result: enter image description here

  • Related