Search code examples
c#linq.net-coredynamic-linq

Using ternary operator/conditional on select on dynamic linq


I am looking to do a linq query with Dynamic Linq library, but I am trying to select a property which is an IEnumerable<T> collection which throws an exception when calling the Sum() function in dynamic linq. I am wondering if I could say something like this:

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


Solution

  • 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