Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

c# - How to map IGrouping<T, K> to IGrouping<T, V> using Linq?

I have a sample object with some properties

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>>. I want to map each group to be of type IGrouping<string, string> by picking myObject.Foo + myObject.Bar from the object class. So the final result would be IEnumerable<IGrouping<string, string>>.

I tried to start with a 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you simply want to regroup everything a solution is to "unroll" the grouping (with .SelectMany) and the "regroup" it.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...