Correct way to retrieve a sum of the earnest money deposits

Discussions related to custom development with Select.
Post Reply
kwesterlage
Posts: 73
Joined: Thu May 21, 2015 2:28 pm

Correct way to retrieve a sum of the earnest money deposits

Post by kwesterlage »

We are (successfully in many cases) using this code to retrieve the difference between the amount of earnest money kept vs returned for an order:

Code: Select all

((IEnumerable<dynamic>)order.SalesContract?.EarnestMoney.Deposits)?.Sum(x => (decimal)x.Amount - (decimal)x.AmountReturnedToBuyer) ?? 0;
Sometimes this code returns strange errors, like:
"Index was out of range. Must be non-negative and less than the size of the collection."
or "Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type."

What is the correct and reliable way to sum the difference between the kept and returned amount for all earnest money deposits on an order?
BobRichards
Posts: 1377
Joined: Wed Jan 15, 2014 3:50 pm
Location: Raleigh, NC
Contact:

Re: Correct way to retrieve a sum of the earnest money depos

Post by BobRichards »

Dynamic types are handy tool and we use them also. However, all types used in LINQ expression must be resolved at compile time (even when using dynamic types) and the c# compiler cannot see the most of the types in the Select order model so it might guess incorrectly (or usually throws up its hands and says "Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type").

The best approach (and *slightly* faster) is to use the IOrderItem interface to get property values. As you will see below, the inner loop still uses dynamic typing because it is so handy.

Code: Select all

// Initialize summation.
decimal amount = 0;

// Get deposits and sum amount of deposit retained.
IOrderItem salesContract = (IOrderItem)iOrder.GetProperty("SalesContract");
if (salesContract != null)
{
	IOrderItem earnestMoney = (IOrderItem)salesContract.GetProperty("EarnestMoney");
	IList deposits = (IList)earnestMoney.GetProperty("Deposits");
	foreach (dynamic deposit in deposits)
	{
		amount += deposit.Amount - deposit.AmountReturnedToBuyer;
	}
}
Bob Richards, Senior Software Developer, SoftPro
Post Reply