C# – cannot implicitly convert type when groupby

clinq

I get this error when I try to group by CellID:

Cannot implicitly convert type 'System.Collections.Generic.List
System.Linq.IGrouping int,p2pControllerLogAnalyser.Models.GSMData' to
'System.Collections.Generic.List
p2pControllerLogAnalyser.Models.GSMData'

public List<GSMData> GetCellID()
{
    return Gsmdata.GroupBy(x => x.CellID).ToList();
}

What am I doing wrong and how can I fix it?

Best Answer

If you really need to do this, though I can't imagine why, you'll need to flatten the per-group enumerables into a single list using SelectMany:

public List<GSMData> GetCellID()
{
    return Gsmdata
        .GroupBy(x => x.CellID)
        .SelectMany(gr => gr)
        .ToList();
}

Of course, this looks like you are trying to batch items with the same CellID together, so you could always simply order it:

public List<GSMData> GetCellID()
{
    return Gsmdata
        .OrderBy(x => x.CellID)
        .ToList();
}


Further to your comments, distinct CellID values can be returned thus:

return Gsmdata.Select(x => x.CellID).Distinct();

If you wish to return an ID and a count of grouped data, you can bundle that into an anonymous type:

return Gsmdata
    .GroupBy(x => x.CellID)
    .Select(gr => new { CellID = gr.Key, Count = gr.Count() });

Though if you are returning this from a method I'd make a discoverable type and not use an anonymous type.