Hi All,
I know it's a highly subjective issue (and one that may well see a flurry of 'close it' votes), hence pointing it at the CW and adding the disclaimer.
Anyway, I've been working thro a project in asp.net mvc using subsonic and was suddenly (again) struck with the elegence and 'ruggedness' of the linq implementation that lies on top of both subsonic and the general linq to objects library. This occasioned me look a little closer into my code and made me realise that some of the tasks that I was using linq for would be endlessly complex (or 'near impossible' - subjective of course) if attempted in a traditional manner (this of course could well be a limitation in me).
Anyway, as a result of this, I thought it would be interesting to see what problems folk had encountered that were elegently solved by using linq.
To kick off, one scenario that i recently had involved an entity that had a common 'unitid' property on it. i wanted to be able to group a set of these in order to manipulate and examine this set when split out to thier appropriate 'unitid' groups. After much thought, i arrived at this simple little linq one liner:
// the base collection of the objects - not grouped in any way
IQueryable<ShareholderRSP> rsps = validshareholderPounds
.Where(x => x.Balance > 0)
.OrderBy(x => x.RequestYear);
// the one-liner in question to group the objects by unitid
IList<IGrouping<string, ShareholderRSP>> groupedRSP =
rsps.ToList().GroupBy(t => t.UnitID.ToString()).ToList();
which i was then able to use as:
foreach (var rspGrpItem in groupedRSP)
{
foreach (var shareholderRSP in rspGrpItem)
{
// note, i could have also iterated this list too
// which is a base object contained within the collection
// underneath the group collection item
}
// create a top level summary grouped by unitid
// usedPounds is a variable created earlier on in the piece
bookingConfirm.RSPUnitSelect.Add(
new BookingConfirmRSPSelect
{
TotalBeforeUse = rspGrpItem.Sum(rsp => rsp.Balance),
TotalAfterUse = rspGrpItem.Sum(rsp => rsp.Balance) - usedPounds,
UnitNo = rspGrpItem.Key
}
);
}
Had i attempted this in a traditional fashion, my logic would (in my opinion) have been more cumbersome and less able to adapt to any changes in the underlying object model.
Hopefully, if not quite a discussion sparker, this has highlighted my 'joy' at using linq.
All the best - hopefully the omission of the object model in question above won't detract from the purpose of the example, as hopefully the intention reveals all.
Looking fwd to some fine examples.
jim