Linq select to new object

前端 未结 6 1829
攒了一身酷
攒了一身酷 2020-12-09 07:45

I have a linq query

var x = (from t in types select t).GroupBy(g =>g.Type)

which groups objects by their type, as a result I want to ha

6条回答
  •  囚心锁ツ
    2020-12-09 08:07

    Read : 101 LINQ Samples in that LINQ - Grouping Operators from Microsoft MSDN site

    var x = from t in types  group t by t.Type
             into grp    
             select new { type = grp.key, count = grp.Count() };
    

    forsingle object make use of stringbuilder and append it that will do or convert this in form of dictionary

        // fordictionary 
      var x = (from t in types  group t by t.Type
         into grp    
         select new { type = grp.key, count = grp.Count() })
       .ToDictionary( t => t.type, t => t.count); 
    
       //for stringbuilder not sure for this 
      var x = from t in types  group t by t.Type
             into grp    
             select new { type = grp.key, count = grp.Count() };
      StringBuilder MyStringBuilder = new StringBuilder();
    
      foreach (var res in x)
      {
           //: is separator between to object
           MyStringBuilder.Append(result.Type +" , "+ result.Count + " : ");
      }
      Console.WriteLine(MyStringBuilder.ToString());   
    

提交回复
热议问题