如何将c# linq中的groupby看作是一个二维列表


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();

调用"a"在"2016,2,2"处的"Close"值的最简单方法是什么,是否可以使用像StockGroupList[0][1].close这样的东西?

其次,如何对第二次元排序?例如,对于每个"符号",按日期顺序排序?

让我们倒着写代码。为了使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以获得相同的效果

尝试执行两次.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

相关内容

  • 没有找到相关文章

最新更新