LINQ的选择新对象 [英] Linq select to new object
本文介绍了LINQ的选择新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个LINQ查询
var x = (from t in types select t).GroupBy(g =>g.Type)
这组按类型的对象,因此我希望能有一个新的对象包含所有组合的对象和他们的计数。事情是这样的:
which groups objects by their type, as a result I want to have single new object containing all of the grouped objects and their count. Something like this:
type1, 30
type2, 43
type3, 72
更清晰:分组结果应该是一个对象而不是每个项目类型的对象
to be more clear: grouping results should be in one object not an object per item type
推荐答案
阅读: 101 LINQ样品 在 LINQ - 微软MSDN分组操作符网站
var x = from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() };
forsingle对象使用的StringBuilder并追加它,会做或转换这字典的形式
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());
这篇关于LINQ的选择新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文