我是编程新手。我正在从我的数据库中检索列价格并将其保存到列表中。我想对那些数据执行一些乘法,并希望在乘法后将结果存储到另一个列表中。这是我编写的用于获取数据并将其存储到列表中的代码。
SqlDataAdapter da = new SqlDataAdapter("Select Price from FoodPackages",con);
DataSet dataset = new DataSet();
da.Fill(dataset, "FoodPackages");
List<int> package_price = new List<int>();
foreach(DataRow row in dataset.Tables["FoodPackages"].Rows)
{
package_price.Add(Convert.ToInt32(row["Price"]));
}
for( int i = 0; i<package_price.Count; i++)
{
int food = guest * package_price[i]; // Food = The total food cost
}
我将客人与列表的每个元素相乘的行。这里我有一个整数变量但不是这个我想要一个列表。请帮助我这样做。
提前致谢
答案 0 :(得分:2)
如果我理解你是这样的:
SqlDataAdapter da = new SqlDataAdapter("Select Price from FoodPackages",con);
DataSet dataset = new DataSet();
da.Fill(dataset, "FoodPackages");
List<int> package_price = new List<int>();
foreach(DataRow row in dataset.Tables["FoodPackages"].Rows)
{
package_price.Add(Convert.ToInt32(row["Price"]));
}
// Initialize a new list
List<int> myList = new List<int>();
for( int i = 0; i<package_price.Count; i++)
{
int food = guest * package_price[i]; // Food = The total food cost
// Add element into the list
myList.Add(food);
}
ADD :如果“guest”变量不是int类型,则必须创建十进制列表:
List<decimal> myList = new List<decimal>();
for( int i = 0; i<package_price.Count; i++)
{
//int food = guest * 20; // this line is not necessary
// You can calculate and add element into the list at once
myList.Add(guest * 20);
}