Reputation: 121
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?
Upvotes: 5
Views: 20842
Reputation: 13381
if i understand right you need something like this
var result = (from gdata in Gsmdata
group gdata by gbata.CellID into g
select new Result{
CellID = g.Key,
Meters = g.Sum(i=>i.Meter)
}
).ToList();
where Result
is
public class Result{
public /*type your CellID */ CellID;
public /*type your Meter */ Meters;
}
Upvotes: 1
Reputation: 64517
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();
}
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.
Upvotes: 12
Reputation: 22491
The problem is that GroupBy returns a grouped collection, in this case System.Collections.Generic.List<System.Linq.IGrouping<int, p2pControllerLogAnalyser.Models.GSMData>>
. Your method returns a List<GSMData>
.
In order to fix this, you need to adjust your method declaration and/or your Linq query so that the types match.
From your comments, I understand that you want to return a list of the distinct cell ids. You can do this by changing both the method declaration and the Linq query (I'm assuming that CellID is of type int
based upon the type in the IGrouping):
public List<int> GetCellID()
{
return Gsmdata.Select(x => x.CellID)
.Distinct().ToList();
}
Upvotes: 0