在 IGrouping 中创建 IGrouping

Create IGrouping within IGrouping

我有一套List的公寓ViewModels

var initialList = new List<ViewModel>
{
    new ViewModel { OuterCaption = "A outer", InnerCaption = "A inner", Caption = "E", Id = 8},
    new ViewModel { OuterCaption = "B outer", InnerCaption = "B inner", Caption = "A", Id = 5},
    new ViewModel { OuterCaption = "A outer", InnerCaption = "B inner", Caption = "A", Id = 12},
    new ViewModel { OuterCaption = "B outer", InnerCaption = "B inner", Caption = "B", Id = 9},
    new ViewModel { OuterCaption = "A outer", InnerCaption = "B inner", Caption = "B", Id = 23},
    new ViewModel { OuterCaption = "B outer", InnerCaption = "C inner", Caption = "A", Id = 10},
    new ViewModel { OuterCaption = "A outer", InnerCaption = "B inner", Caption = "C", Id = 16},
    new ViewModel { OuterCaption = "A outer", InnerCaption = "A inner", Caption = "C", Id = 4},
    new ViewModel { OuterCaption = "A outer", InnerCaption = "A inner", Caption = "D", Id = 7},
    new ViewModel { OuterCaption = "C outer", InnerCaption = "A inner", Caption = "A", Id = 31},
    new ViewModel { OuterCaption = "B outer", InnerCaption = "A inner", Caption = "A", Id = 19},
    new ViewModel { OuterCaption = "B outer", InnerCaption = "A inner", Caption = "B", Id = 20},
    new ViewModel { OuterCaption = "A outer", InnerCaption = "A inner", Caption = "A", Id = 1},
    new ViewModel { OuterCaption = "A outer", InnerCaption = "A inner", Caption = "B", Id = 3}
}.OrderBy(vm => vm.OuterCaption).ThenBy(vm => vm.InnerCaption).ThenBy(vm => vm.Caption);

其中每个ViewModel如下

class ViewModel
{
    public string OuterCaption { get; set; }
    public string InnerCaption { get; set; }
    public string Caption { get; set; }
    public int Id { get; set; }

}

现在我想将 ListOuterCaption 分组,然后再按 InnerCaption 分组。我可以像这样将 ListOuterCaption 分组。

var list = initialList.GroupBy(vm => vm.OuterCaption).ToList();

并像这样在我的 View 中使用它,并在我的 View.

中使用 GroupBy
foreach (var outerGrouping in list)
{
    Console.WriteLine(outerGrouping.Key);
    Console.WriteLine("~~~~~~~~~~~~~~~~~~");

    foreach (var innerGrouping in outerGrouping.GroupBy(vm => vm.InnerCaption))
    {
        Console.WriteLine(innerGrouping.Key);

        foreach (var vm in innerGrouping)
        {
            Console.WriteLine("Caption: " + vm.Caption + " Id:" + vm.Id);
        }

        Console.WriteLine("------------------");
    }

    Console.WriteLine("~~~~~~~~~~~~~~~~~~");
}

但我想在 IGrouping 中创建一个 IGrouping,而不是在我的 View 中使用 GroupBy(或 Linq)。我确实认为我应该为我的 View 创建类似 IReadOnlyList<IGrouping<string, IGrouping<string, ViewModel>>> 的东西(可能是错误的)。我如何用我的 initialList 实现这一点,以便我可以从我的 View?

中删除 Linq

示例代码如下:https://dotnetfiddle.net/hP2kxO

这是有效的。这不是我要找的东西,但它从我的 View.

中删除了 Linq
var list = initialList
    .GroupBy(vm => (vm.OuterCaption, ViewModel: vm))
    .GroupBy(group => group.Key.ViewModel.InnerCaption)
    .ToList();