GroupBy使List <T>成为List <List <T >>

Jim*_*988 -2 c# linq

我有以下内容:

List<Something> somethings = new List<Something>()
{
    new Something(){ Connection = "Bob" },
    new Something(){ Connection = "Bob" },
    new Something(){ Connection = "Peter" },
}
Run Code Online (Sandbox Code Playgroud)

我想最终得到以下结论:

List<List<<Something>> groupedSomethings = new List<List<<Something>>()
    new List<Something>()
    {
        new Something(){ Connection = "Bob" },
        new Something(){ Connection = "Bob" }
    }
    new List<Something>()
    {
        new Something(){ Connection = "Peter" },
    }
}
Run Code Online (Sandbox Code Playgroud)

我无法正确地获得Linq声明.

我想它看起来像这样:

List<List<<Something>> groupedSomethings = somethings
    .GroupBy(x => x.Connection)
    .SelectMany(somethings => new List<Something>());
Run Code Online (Sandbox Code Playgroud)

你会怎么做?

Pat*_*man 6

您可以使用GroupBy,然后从组中获取值:

var lists = somethings.GroupBy(x => x.Connection).Select(g => g.ToList()).ToList();
Run Code Online (Sandbox Code Playgroud)