我有一个带有一些属性的样例对象
public class MyObject
{
public string Foo { get; set; }
public string Bar { get; set; }
}
我在一个集合上使用了GroupBy
Linq方法,现在有了一个IEnumerable<IGrouping<string, MyObject>>
。我希望通过从对象类中选择IGrouping<string, string>
来将每个组映射为myObject.Foo + myObject.Bar
类型。因此,最终结果将是IEnumerable<IGrouping<string, string>>
。
我试着从Select
开始
IEnumerable<IGrouping<string, MyObject>> oldCollection = null;
IEnumerable<IGrouping<string, string>> newCollection = oldCollection
.Select(oldGroup =>
{
IGrouping<string, string> newGroup = null;
// pick the key from the oldGroup via oldGroup.Key
// map the values from oldGroup to strings, sample code:
// newGroup.Values = oldGroup.Select(myObject => myObject.Foo + myObject.Bar);
return newGroup;
});
如何在该语句中将oldGroup
映射到newGroup
?
发布于 2021-01-06 18:55:47
如果您只是想对所有内容进行重新组合,那么解决方案就是“展开”分组(使用.SelectMany
),然后对其进行“重新组合”。
var regrouped = grouped
.SelectMany(x => x, (x, y) => new { x.Key, Sum = y.Foo + y.Bar })
.GroupBy(x => x.Key, x => x.Sum);
显然,也许您可以简单地“正确”地构建分组?
var grouped = collection.GroupBy(x => x.Foo, x => new { x.Foo + x.Bar });
这里有一个重载的.GroupBy
,第二个参数设置每个组元素的“内容”。
https://stackoverflow.com/questions/65594289
复制相似问题