问题
I am unable to convert back var
to List<CustomObject>
.
private void PopulateChart(List<CustomObject> rawData)
{
var groupedByCategory1 = rawData.GroupBy(co => co.Category1)
//List<CustomObject> data = groupedByCategory1.GroupBy(co => co.Category1).ToList();
}
Note: From rawData
I have to get Groupby data. using that result again I have to group the data.
回答1:
Linq GroupBy
returns System.Linq.IQueryable<IGrouping<TKey,TSource>>
. So, you should select some data from groups:
List<CustomObject> data = groupedByCategory1
.GroupBy(co => co.Category1)
.Select(grp => new CustomObject
{
Category1 = grp.Key
}
.ToList();
回答2:
var data = groupedByCategory1
.GroupBy(co => co.Category1)
.Select(grp => new
{
Category1 = grp.Key// This is the key that you used to group
groupList=grp.ToList();//This will be the list of CustomObject
}
.ToList();
Actually, GroupBy
groups your list into another list where Category1
is same.
You can access it as shown below
foreach (var group in data)
{// This group is List<CustomObject>. If you don't want to access it like this, whats the meaning of group by?
var groupKey=group.Category1;
foreach(CustomObject myObj in group.groupList)
{
}
}
回答3:
Have you tried
var groupedByCategory1 = rawData
.GroupBy(co => co.Category1)
.SelectMany(c => c)
.ToList();
来源:https://stackoverflow.com/questions/22627426/convert-var-to-listt-in-c-sharp