gpt4 book ai didi

c# - 在 select 语句中调用 Helperfunction,保留多个值的返回结果

转载 作者:行者123 更新时间:2023-11-30 21:03:22 24 4
gpt4 key购买 nike

我正在构建一个 JSON 字符串,在行部分中,我有两个值要构建并传入 JSON 字符串,这两个值由辅助函数计算得出。我想知道是否有一种方法可以调用此辅助函数一次,并返回一个值数组(在我的例子中是两个值),这样我就不必两次调用辅助函数(并避免访问数据库两次)。

示例代码

            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()

示例函数:

public decimal GetPrice(int ID, bool Premium)
{
Item item = databaseCallToGetPrice(ID).first();

if (Premium)
return item.ExamplePrice;
else
return item.PremiumExamplePrice;
}

因此,我要问的是,在我的示例中,我调用了 Helper 函数两次,有没有办法只调用一次,然后返回一个数组,我可以以某种方式保留该数组,然后使用两次。

最佳答案

返回 Tuple<decimal, decimal>来自函数:

public Tuple<decimal, decimal> GetPrices(int ID)
{
Item item = databaseCallToGetPrice(ID).First();
return Tuple.Create(item.ExamplePrice, item.PremiumExamplePrice);
}

然后使用它:

rows = (
from tempItem in pagedQuery.ToList()
let prices = HelpererFunction.GetPrices(tempItem.ID)
select new
{
cell = new string[] {
tempItem.Name,
tempItem.Regular,
prices.Item1.ToString(),
tempItem.Premium,
prices.Item2.ToString(),
}
}).ToArray()

恕我直言,元组优于简单数组,因为您可以保证从函数返回两项且仅两项。


如果你想更清楚,你可以创建一个结构

public struct Prices
{
public decimal PremiumPrice, Price;

public Prices(decimal premium, decimal price)
{
PremiumPrice = premium;
Price = price;
}
}

然后从辅助函数返回它

public Prices GetPrices(int ID)
{
Item item = databaseCallToGetPrice(ID).First();
return new Prices(item.PremiumExamplePrice, item.ExamplePrice);
}

并使用它:

rows = (
from tempItem in pagedQuery.ToList()
let prices = HelpererFunction.GetPrices(tempItem.ID)
select new
{
cell = new string[] {
tempItem.Name,
tempItem.Regular,
prices.Price.ToString(),
tempItem.Premium,
prices.PremiumPrice.ToString(),
}
}).ToArray()

关于c# - 在 select 语句中调用 Helperfunction,保留多个值的返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12938177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com