patterncsharpMinor
A better way to do LINQ projections
Viewed 0 times
projectionslinqwaybetter
Problem
I was wondering if there's a better way of doing LINQ projections than what I'm doing below. This method is one of many methods creating a view of an object tree.
The first thing that I don't like is that I'm returning an anonymous object. Should I create a
Also, the copying of property values from right to left is a bit of a hassle.
The first thing that I don't like is that I'm returning an anonymous object. Should I create a
BreakdownReport class or something else instead?Also, the copying of property values from right to left is a bit of a hassle.
public object GetBreakdownsReport()
{
return CurrentSecurity
.Breakdowns
.SelectMany(b => b.BreakdownLines, (b, bdl) => new
{
AccountId = b.Account.Id,
Structure = b.Account.Structure,
Market = b.Account.Market,
BeneficiaryId = bdl.Beneficiary.Id,
BeneficiaryType = bdl.Beneficiary.BeneficiaryType,
CountryCode = bdl.Beneficiary.CountryCode,
CountryName = bdl.Beneficiary.CountryName,
DtaRate = bdl.Beneficiary.DtaRate,
HoldingCode = b.HoldingCode,
InstructionAmount = bdl.InstructionAmount,
NarrativeText = bdl.Narrative.Text,
Chapter = bdl.Narrative.Chapter,
Paragraph = bdl.Narrative.Paragraph,
Subparagraph = bdl.Narrative.Subparagraph,
TaxRate = bdl.Narrative.TaxRate,
})
.ToList();
}Solution
There's nothing wrong with this kind of assignment logic per se, but you usually don't want it cluttering up the rest of your application logic so it usually belongs in a constructor method. If you're using the
GetBreakDownsReport() method to construct the source for a datagrid, replace your anonymous object with a BreakdownsReportViewModel object and make a constructor that handles all property assignments. This will have the added benefit of making your GetBreakdownsReport() method signature more expressive and easier to read.Context
StackExchange Code Review Q#58044, answer score: 4
Revisions (0)
No revisions yet.