Thursday, 2 August 2012

C# LINQ Pivot

public void TestLinqPivot()
{
  var before = new []{
    new {Ticker="FB", Type="BID", Value=1},
    new {Ticker="FB", Type="ASK", Value=11},
    new {Ticker="IBM", Type="BID", Value=2},
    new {Ticker="IBM", Type="ASK", Value=22}
  };
 
  Console.WriteLine("Ticker,Type,Value");
  foreach (var item in before)
  {
    Console.WriteLine("{0},{1},{2}", item.Ticker, item.Type, item.Value);
  }
 
  var after = before.GroupBy(x => x.Ticker).Select(
    x => new
          {
            Ticker = x.Key,
            BID = x.Where(y => y.Type.Equals("BID")).Sum(y => y.Value),
            ASK = x.Where(y => y.Type.Equals("ASK")).Sum(y => y.Value)
          });
 
  Console.WriteLine();      
  Console.WriteLine("Ticker,BID,ASK");
  foreach (var item in after)
  {
    Console.WriteLine("{0},{1},{2}", item.Ticker, item.BID, item.ASK);
  }
}
Ticker,Type,Value
FB,BID,1
FB,ASK,11
IBM,BID,2
IBM,ASK,22
 
Ticker,BID,ASK
FB,1,11
IBM,2,22

No comments:

Post a Comment