Still learning Linq here. So I've got a class that looks like this (comes from a db table):
class FundRaisingData { public double funds { get; set; } public DateTime date { get; set; } public string agentsGender { get; set; } } What I need to do is transform this to list of anonymous objects that looks something like this (it will be transformed and returned as JSON later ). I know this is not an anonymous object, but it will give you some idea of what I'm trying to do:
class groupedFunds { public string gender { get; set; } public List<double> fundsRaised { get; set; } } So I need to figure out how I can sum the funds for each year in the right order (2010-2014).
Eventually it should look like this in JSON:
ListOfGroupedFunds[ { "gender" : "Female", "fundsRaised" : [2000, 2500, 3000] }, { "gender" : "Male", "fundsRaised": [4300,2300,3100] } ]; So fundsRaised[0] would correspond to 2012, fundsRaised[1] would correspond to 2013, etc. but not actually say "2013" anywhere in the object.
I've read a ton of articles today on Linq and searched through similar StackOverflow articles but I still just can't quite figure it out. Any help in pointing me in the right direction would be awesome.
-- Edit 2 (changing code more closely match solution) --
I think the code by Mike worked well, but because I'm not sure how many years there will be in advance I've modified it slightly:
var results = data.GroupBy(g=> Gender = g.agentsGender) .Select(g=> new { gender = g.Key years = g.GroupBy(y=> y.Date.Year) .OrderBy(y=> y.Key) .Select(y=> y.Sum(z=> z.funds)) .ToArray() }) .ToArray(); Is there anything wrong about the above? It seems to work but I'm open to better solutions of course.