如何将C# linq中的groupby视为二维列表?

how to regard groupby in C# linq as a two dimensional list?

List<History> data = new List<History>(){   
        new History() {Symbol="a", Close = 1.0m, Date = new DateTime(2016, 2, 1) },
        new History() {Symbol="a", Close = 1.2m, Date = new DateTime(2016, 2, 2) },
        new History() {Symbol="a", Close = 1.3m, Date = new DateTime(2016, 2, 3) },
        new History() {Symbol="b", Close = 1.2m, Date = new DateTime(2016, 2, 1) },
        new History() {Symbol="b", Close = 1.2m, Date = new DateTime(2016, 2, 2) },
        new History() {Symbol="b", Close = 1.3m, Date = new DateTime(2016, 2, 3) },
};

var StockGroupList = data
               .GroupBy(o => o.Symbol)
               .OrderBy(o => o.Key)
               .ToList();

在“2016, 2, 2”处调用 "a" 的 "Close" 的值的最简单方法是什么,是否可以使用类似 StockGroupList[0][1] 的方法。关闭?

另外,二次元如何排序?例如,对于每个 "Symbol",按日期顺序排序?

尝试.ToList()两次:针对每个组中的项目和所有组作为一个整体

  var StockGroupList = data
    .GroupBy(o => o.Symbol)
    .OrderBy(chunk => chunk.Key)
    .Select(chunk => chunk
       .OrderBy(item => item.Date) // ordered by the sequence of date
       .ToList()) // items in a group should be represented as List
    .ToList(); // groups should be represented as List

让我们向后写代码。 要使 StockGroupList[0][1] 工作,StockGroupList 的类型应为 List<List<History>>

var StockGroupList = data
    ... // Should be type IEnumerable<List<History>>
    .ToList();

=>

var StockGroupList = data 
    .Select( o => o.ToList()) // Should be ordered by Date
    .ToList();

=>

var StockGroupList = data 
    ... // Should be IEnumerable<IEnumerable<History>>
    .Select( o => o.Orderby(c => c.Date).ToList())
    .ToList();

因为IGrouping<out TKey, out TElement> : IEnumerable<TElement>,最终代码是

var StockGroupList = data
    .GroupBy(o => o.Symbol)
    .OrderBy(o => o.Key)
    .Select(o => o.OrderBy(x => x.Date).ToList())
    .ToList();

您可以将 ToList 替换为 ToArray 以获得相同的效果。