I have this code:
invoiceSurcharges.Result = from surcharge in invoiceSurcharges.Result
select new ListInvoiceSurchargesGridByInvoice
{
};
Now, I would like to modify just one property of surcharge without having to assign each property of the object to the new one. It would be ideal if I could do something like:
invoiceSurcharges.Result = from surcharge in invoiceSurcharges.Result
select new ListInvoiceSurchargesGridByInvoice
{
...surcharge,
AssociatedInvoice = $"{surcharge.InvoiceSerial}-{surcharge.InvoiceYear}"
};
Is there any way I could do this in C#?
Add a copy constructor to ListInvoiceSurchargesGridByInvoice that copies all the properties from the sucharge object. You can still use property initializers to override specific properties. Consider making your objects immutable, and properties init-only, that helps avoid unintended mutation of your objects.
But an easier method is probably to use records, they are trivial to make immutable, and come with the with-expression to help creating copies with a minimal of boiler plate code:
public record ListInvoiceSurchargesGridByInvoice{
public string AssociatedInvoice { get; init; }
...
}
invoiceSurcharges.Result = from surcharge in invoiceSurcharges.Result
select surcharge with { AssociatedInvoice = $"{surcharge.InvoiceSerial}-{surcharge.InvoiceYear}"};
There are some caveats when using records with EntityFramework. If that is a concern I would recommend doing some further research.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With