Search code examples
linqlinq-to-objectsanonymous-typesprojection

How to project simple data set into to anonymous type of a different shape


I have a simple set of data that I am having trouble figuring out how to create the projection I want using LINQ.

public class Score {
  public string Name { get; set; }
  public int Value { get; set; }
}

var scores = new List<Score> {
  new Score { Name = "jesse", Value = 10 },
  new Score { Name = "jesse", Value = 12 },
  new Score { Name = "jesse", Value = 15 },
  new Score { Name = "billy", Value = 5 },
  new Score { Name = "billy", Value = 7 },
  new Score { Name = "billy", Value = 20 },
  new Score { Name = "colin", Value = 25 },
  new Score { Name = "colin", Value = 13 },
  new Score { Name = "colin", Value = 8 }
};

I need to project 'scores' into an anonymous type with the following structure.

{
  series : [
    { name : "jesse", data : [10, 12, 15 ] },
    { name : "billy", data : [ 5,  7, 20 ] },
    { name : "colin", data : [25, 13,  8 ] }
  ]
}

Any help is appreciated.


Solution

  • var result = new {
        series = from score in scores
               group score.Value by score.Name into nameValues
               select new
               {
                 name = nameValues.Key,
                 data = nameValues
               }
    };