将var转换为List<在c#
本文关键字:List var 转换 | 更新日期: 2023-09-27 17:53:08
我无法将var
转换回List<CustomObject>
。
private void PopulateChart(List<CustomObject> rawData)
{
var groupedByCategory1 = rawData.GroupBy(co => co.Category1)
//List<CustomObject> data = groupedByCategory1.GroupBy(co => co.Category1).ToList();
}
注意:从rawData
我必须得到Groupby数据。使用这个结果,我必须再次对数据进行分组。
Linq GroupBy
返回System.Linq.IQueryable<IGrouping<TKey,TSource>>
。因此,您应该从组中选择一些数据:
List<CustomObject> data = groupedByCategory1
.GroupBy(co => co.Category1)
.Select(grp => new CustomObject
{
Category1 = grp.Key
}
.ToList();
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();
实际上,GroupBy
将您的列表分组到Category1
相同的另一个列表中。
您可以如下所示访问它
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)
{
}
}
你试过了吗
var groupedByCategory1 = rawData
.GroupBy(co => co.Category1)
.SelectMany(c => c)
.ToList();