我有一个linq查询
var x = (from t in types select t).GroupBy(g =>g.Type)
Run Code Online (Sandbox Code Playgroud)
它按类型对对象进行分组,因此我想要包含所有分组对象及其计数的单个新对象.像这样的东西:
type1, 30
type2, 43
type3, 72
Run Code Online (Sandbox Code Playgroud)
更清楚:分组结果应该在一个对象中,而不是每个项目类型的对象
Pra*_*ana 34
阅读:LINQ中的101个LINQ示例 -来自Microsoft MSDN站点的分组操作员
var x = from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() };
Run Code Online (Sandbox Code Playgroud)
forsingle对象使用stringbuilder并附加它将以字典的形式执行或转换它
// 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());
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 31
所有分组对象或所有类型?听起来你可能只想要:
var query = types.GroupBy(t => t.Type)
.Select(g => new { Type = g.Key, Count = g.Count() });
foreach (var result in query)
{
Console.WriteLine("{0}, {1}", result.Type, result.Count);
}
Run Code Online (Sandbox Code Playgroud)
编辑:如果你想在字典中,你可以使用:
var query = types.GroupBy(t => t.Type)
.ToDictionary(g => g.Key, g => g.Count());
Run Code Online (Sandbox Code Playgroud)
没有必要选择成对然后构建字典.
dck*_*ehn 29
这里的答案让我很接近,但在2016年,我能够编写以下LINQ:
List<ObjectType> objectList = similarTypeList.Select(o =>
new ObjectType
{
PropertyOne = o.PropertyOne,
PropertyTwo = o.PropertyTwo,
PropertyThree = o.PropertyThree
}).ToList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
185153 次 |
| 最近记录: |