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

What's the simplest way to call for the value of "Close" of "a" at "2016, 2, 2", is it possible to use something like StockGroupList[0][1].close?

Furthermore, how to order the second dimension? E.g, for each "Symbol", ordered by the sequence of date?

ekad
  • 14,436
  • 26
  • 44
  • 46
user6703592
  • 1,004
  • 1
  • 12
  • 27

2 Answers2

2

Let write code backward. To make StockGroupList[0][1] work, StockGroupList should be type of 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();

Because IGrouping<out TKey, out TElement> : IEnumerable<TElement>, final code is

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

You can replace ToList with ToArray to get the same effect.

qxg
  • 6,955
  • 1
  • 28
  • 36
1

Try doing .ToList() twice: for items in each group and for all groups as a whole

  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
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    _E.g, for each "Symbol", ordered by the sequence of date_ - Add also an `OrderBy` for the `chunk.ToList()` - – Gilad Green Aug 11 '16 at 07:35
  • @Gilad Green: thank you! You've overlooked this phrase – Dmitry Bychenko Aug 11 '16 at 07:38
  • you posted it a moment before I did - so just gave it as a comment instead of an answer :) – Gilad Green Aug 11 '16 at 07:42
  • Thanks! If I want create a new List like select new { Symbol, Close, Date, Vol}; Here "Vol" is the two day standard deviation e.g Vol of Symbol="a" at "2016, 2, 3" is function of "close" for "2016, 2, 3" and "2016, 2, 2". Moreover, The Vol of first day (e.g "2016, 2, 1") is default as Vol = 0. – user6703592 Aug 11 '16 at 08:19