Convert var to List<T> in c#

亡梦爱人 提交于 2019-12-23 04:44:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!