Search code examples
c#linqgroup-bydefaultifempty

Why is this defaultIfEmpty choosing ienumerable<char> instead of string?


 from a in mainDoc.XPathSelectElements("//AssembliesMetrics/Assembly/@Assembly")
                            let aVal=a.Value
                            where aVal.IsNullOrEmpty( )==false&&aVal.Contains(" ")
                            select aVal.Substring(0, aVal.IndexOf(' '))
                              into aName
                              let interestedModules=new[ ] { "Core", "Credit", "Limits", "Overdraft" }
                              where aName.Contains(".")
                              let module=
                                interestedModules
                                .FirstOrDefault(x => aName
                                  .StartsWith(x, StringComparison.InvariantCultureIgnoreCase))
                              where module!=null
                              group aName by module.DefaultIfEmpty() // ienumerable<char>, why?
                                into groups
                                select new { Module=groups.Key??"Other", Count=groups.Count( ) };

Solution

  • module is a string.

    String implements IEnumerable<char>.

    You're calling the Enumerable.DefaultIfEmpty method, which extends IEnumerable<T>.
    This method can never return anything other than an IEnumerable<T>.

    EDIT: If you want to replace null values of module with a non-null value, you can use the null-coalescing operator:

    group aName by module ?? "SomeValue"
    

    However, module will never actually be null, because of the where module!=null clause.
    You should then also remove ??"Other" from the final select clause.