I am building a JSON string and in the rows section, I have two values that I want to build and pass in the JSON string which are calculated by a helper function. I am wondering if there a way to call this helper function once, and return back an array of values (two in my case) so I don’t have to call the helper function twice (and avoid hitting the database twice).
Example Code
rows = (
from tempItem in pagedQuery.ToList()
select new
{
cell = new string[] {
tempItem.Name,
tempItem.Regular,
HelperFunction.GetPrice(tempItem.ID, false).ToString(),
tempItem.Premium,
HelperFunction.GetPrice(tempItem.ID, true).ToString(),
}
}).ToArray()
Example Function:
public decimal GetPrice(int ID, bool Premium)
{
Item item = databaseCallToGetPrice(ID).first();
if (Premium)
return item.ExamplePrice;
else
return item.PremiumExamplePrice;
}
So what I am asking is in my example I call the Helper function twice, is there a way to call on it just the once and then return back an array that I can somehow persist and then use twice.
Return a
Tuple<decimal, decimal>from the function:Then use that:
IMHO a tuple is better than a simple array because you’re guaranteed to get two and only two items back from the function.
If you want to be even clearer, you can create a struct
then return that from the helper function
and use that: