Linq 选择新对象 [英] Linq select to new object
本文介绍了Linq 选择新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 linq 查询
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 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 - Grouping Operators 来自 Microsoft MSDN 站点
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 对象利用 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屋!
查看全文