gpt4 book ai didi

c# - 结合相似的方法

转载 作者:太空宇宙 更新时间:2023-11-03 20:19:47 25 4
gpt4 key购买 nike

我目前有两种方法:

CalculateDaily()
{
List<string> tempList;

// Effective query. not what is really passed
tempList = "SELECT timestamp FROM table1 WHERE date = today";

var total = tempList.Sum();
}

和:

CalculateTotal()
{
List<string> tempList;

// Effective query. not what is really passed
tempList = "SELECT timestamp FROM table1"

var total = tempList.Sum();
}

我的问题是我应该将它们分开,还是将它们组合成一个方法并运行 if 检查是否可行?像这样的东西:

Calculate(bool daily)
{
List<string> tempList;

if(daily)
tempList = "SELECT timestamp FROM table1 WHERE date = today";
else
tempList = "SELECT timestamp FROM table1";

var total = tempList.Sum();
}

最佳答案

我会使用一种提供开始日期和结束日期的方法。然后您可以随意使用它。

public static int Calculate(DateTime startDate, DateTime endDate)
{
string sql = @"SELECT SUM(timestamp)
FROM table1
WHERE date BETWEEN @startDate AND @endDate";
using(var con=new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, con))
{
con.Open();
cmd.Parameters.AddWithValue("@startDate", startDate);
cmd.Parameters.AddWithValue("@endDate", endDate);
int sum = (int)cmd.ExecuteScalar();
return sum;
}
}

关于c# - 结合相似的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14388582/

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