[英]How to map IGrouping<T, K> to IGrouping<T, V> using Linq?
I have a sample object with some properties我有一个带有一些属性的示例 object
public class MyObject
{
public string Foo { get; set; }
public string Bar { get; set; }
}
I used the GroupBy
Linq method on a collection and now have a IEnumerable<IGrouping<string, MyObject>>
.我在集合上使用了
GroupBy
Linq 方法,现在有一个IEnumerable<IGrouping<string, MyObject>>
。 I want to map each group to be of type IGrouping<string, string>
by picking myObject.Foo + myObject.Bar
from the object class.我想通过从 object class 中选择
myObject.Foo + myObject.Bar
来将 map 每个组的类型设为IGrouping<string, string>
。 So the final result would be IEnumerable<IGrouping<string, string>>
.所以最终结果将是
IEnumerable<IGrouping<string, string>>
。
I tried to start with a Select
我尝试从
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;
});
how can I map oldGroup
to newGroup
in that statement?我怎样才能在该声明中将
oldGroup
为newGroup
?
If you simply want to regroup everything a solution is to "unroll" the grouping (with .SelectMany
) and the "regroup" it.如果您只是想重新组合所有内容,则解决方案是“展开”分组(使用
.SelectMany
)并“重新组合”它。
var regrouped = grouped
.SelectMany(x => x, (x, y) => new { x.Key, Sum = y.Foo + y.Bar })
.GroupBy(x => x.Key, x => x.Sum);
Clearly perhaps you could simply have built the grouping "correctly"显然,也许您可以简单地“正确”构建分组
var grouped = collection.GroupBy(x => x.Foo, x => new { x.Foo + x.Bar });
There is an overload of .GroupBy
just for that, with the second parameter that sets the "content" of each group element. .GroupBy
就是为此而重载,第二个参数设置每个组元素的“内容”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.