views:

89

answers:

2

I have a set of Entities which basically has this structure.

{Stats Name="<Product name> (en)" TotalResources="10" ..}
    {DayStats Date="2009-12-10" TotalResources="5"}
    {DayStats Date="2009-12-11" TotalResources="5"}
{Stats}
{Stats Name="<Product name> (us)" TotalResources="10" ..}
    {DayStats Date="2009-12-10" TotalResources="5"}
    {DayStats Date="2009-12-11" TotalResources="5"}
{Stats}
...

What I wan't to extract from this set is a new set entities (or entity in the example above) where the first level has been grouped by the (ignoring the country label) where all/some of the properties has been summmed together, including the the sublist of {DayStas} on a per day basis. So the result set of the example would look something like this:

{Stats Name="<Product name>" TotalResources="20" ..}
    {DayStats Date="2009-12-10" TotalResources="10"}
    {DayStats Date="2009-12-11" TotalResources="10"}
{Stats}
...

So my question is: Is it possible to do this in a more elegant way in LINQ rather than the vanilla "loop-trhough-each-entity-and-compare"-way?

And I wan't the set to contain the same type of entities as the original set ({Stats}, {DayStats}), your answer doesn't need to include code for that, I can probably work that out by myself. Just letting you know incase you need to take that into account.

(I'm sorry if this question has been discussed before, I tried searching to no avail. I guess my searching skills are fuubar ;))

Merry christmas =)

A: 

Try:

 dataset.SelectMany(p => new {stat=p, daystats=p.DayStats)
        .GroupBy(c => c.stat.Name.SubString(0, c.stat.Name.Length - 5))
Wouter
I think you missed the essence of the question. The troublesome part is the summation of the entity properties and the sublist.But thanks anyway!
mikei
I realised, hope this helps more :)
Wouter
A little, but not all the way, atleast to my understanding. I fail to se how this summs the entity properties both on the first level and the second level?
mikei
A: 

A little late, but maybe still useful. RemoveCountry should be an extension method that returns the name of the Stats without the country suffix.

IEnumerable<Stats> aggregated =
    from stat in stats
    group stat by stat.Name.RemoveCountry() into grp
    select new Stats
    {
        Name = grp.Key,
        TotalResources = (from stat in grp select stat.TotalResources).Sum(),
        DayStats = (from stat in grp
                    from dayStat in stat
                    group dayStat by dayStat.Date into dgrp
                    select new DayStats
                    {
                        Date = dgrp.Key,
                        TotalResources = (from dayStat in dgrp select dayStat.TotalResources).Sum()
                    }).ToList()
    };
Fede