Hi all,
I have collection of custom objects(assets) which I want to group with LINQ. Custom object has standard properties like id, name and cost property. When grouping I want to calculate cost for each group, so I'm using little trick like this:
from a in assets
group a by a.AssetId into ga
select new Asset()
{
AssetId = ga.Key,
Cost = ga.Select(gg=>gg.Cost).Sum()
}
Ok, everything is fine here. But...in order to initialize order properties as well, I'm using copy contructor and cost calculations together...
from a in assets
group a by a.AssetId into ga
select new Asset(ga.FirstOrDefault())
{
AssetId = ga.Key,
Cost = ga.Select(gg=>gg.Cost).Sum()
}
So now, I get collection of grouped assets by id, with all properties copied from a first asset in a group with calculated grouped cost. But...in order to do that I need to write for every object that using this kind of grouping, a copy constructor with 'all properties initialization' which in my case is overhead because there are objects with 20+ properties.
I've tried to use clone trick from a link:
http://stackoverflow.com/questions/78536/cloning-objects-in-c
in linq group query but with no success.
My question: is there a better/more elegant way to accomplish this?
Thank you