将var转换为c#</t>中的List <t>

时间:2014-03-25 06:58:15

标签: c# linq delegates

我无法将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数据。再次使用该结果我必须对数据进行分组。

3 个答案:

答案 0 :(得分:1)

Linq GroupBy返回System.Linq.IQueryable<IGrouping<TKey,TSource>>。因此,您应该从组中选择一些数据:

List<CustomObject> data = groupedByCategory1
     .GroupBy(co => co.Category1)
     .Select(grp => new CustomObject 
          {
              Category1 = grp.Key
          }
     .ToList(); 

答案 1 :(得分:1)

 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)
   {

   }
}

答案 2 :(得分:0)

你试过吗

var groupedByCategory1 = rawData
   .GroupBy(co => co.Category1)    
   .SelectMany(c => c)
   .ToList();