LINQ GroupBy with conditional operator Error: Type of conditional expression cannot be determined

sushma123
 
on May 06, 2021 04:17 AM
1417 Views

I have written below code but it throws an error

var conflictcomments = (item.Key == Constant.SB023) 
    ? item.GroupBy(m => new { m.UserGroup, m.IGGConflict }) 
    : item.GroupBy(m => new { m.CompanyCodeConflict, m.IGGConflict });

Error message:

Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Collections.Generic.IEnumerable<System.Linq.IGrouping<<anonymous type: string UserGroup, string IGGConflict>, Entities.MitigatingControlComments>>' and 'System.Collections.Generic.IEnumerable<System.Linq.IGrouping<<anonymous type: string CompanyCodeConflict, string IGGConflict>, Entities.MitigatingControlComments>>'

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on May 06, 2021 04:31 AM

Hi sushma123,

The conditional operator requires that the return type be the same or an implicit conversion must exist from one type to the other.

The return types of both are of Anonymous type.

Both needs to be same Anonymous type the field names and type must be the same and must appear in the same order.

I am assuming that UserGroup and CompanyCodeConflict are of the same data type.

So you needed is to name the fields of the Anonymous type the same like below. 

var conflictcomments = (item.Key == Constant.SB023) 
    ? item.GroupBy(m => new
    {
        Code: m.UserGroup,
        IGGConflict = m.IGGConflict
    })
    : item.GroupBy(m => new 
    { 
         Code:m.CompanyCodeConflict,
         IGGConflict= m.IGGConflict
    });