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
1.0k views
in Technique[技术] by (71.8m points)

group by - c# grouping list of list by index

I am from python programming and just a little knowledge of c#. I would like to group the following:

    List<List<dynamic>> data = new List<List<dynamic>>();
    data.Add(new List<dynamic> {"a", "z", "m", 4});
    data.Add(new List<dynamic> {"b", "x", "n", 2});
    data.Add(new List<dynamic> {"b", "x", "n", 1});
    data.Add(new List<dynamic> {"c", "y", "n", 3});
    data.Add(new List<dynamic> {"a", "z", "m", 5});
    data.Add(new List<dynamic> {"a", "y", "m", 6});

How can I group the list of list above without using keys only by index? I want the output to be:

    {
     {"a", "z", "m", {4, 5}},
     {"b", "x", "n", {2, 1}},
     {"c", "y", "n", {3}},
     {"a", "y", "m", {6}}
    }
question from:https://stackoverflow.com/questions/65897852/c-sharp-grouping-list-of-list-by-index

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

1 Reply

0 votes
by (71.8m points)

I have used Dennis method.

var lstOutput=data.GroupBy(_ => (_[0], _[1], _[2]), _ => (_[0],_[1],_[2],_[3]))
            .Select(grp => {
                dynamic first=null;
                first = new List<dynamic>(){
                    grp.Key.Item1,
                    grp.Key.Item2,
                    grp.Key.Item3,
                    grp.ToList().Select(x=>x.Item4).ToList()
                };
                return first;
                }).ToList();

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

...