在 Visual Studio 中,使用 C#,我得到了三个如下所示的数组:
int[] price = new int[] { 100, 200, 300, 400, 500, 600 };
string[] goods = new string[] { "item1", "item2", "item3", "item4", "item5", "item6" };
bool[] cart = new bool[] { false, false, false, false, false, false };
bool 购物车代表复选框。现在我想做的是,使用一个按钮来检查勾选了哪些框,然后从数组 goods 中获取项目的名称,并从数组 price 中获取项目的价格。然后我将连接字符串,将总和相加,然后将其显示在 MessageBox.Show 中。
我想我需要以某种方式将购物车数组的索引与价格和商品数组的相应索引相关联。或者有更好的方法吗?可能是一个 for 循环,但是如何呢?我不知道从哪里开始。 帮助非常感谢!
最佳答案
is there a better way of doing this?
像这样的匹配数组是一种反模式,并且表明您真的应该创建一个具有价格、商品和购物车属性的类。然后您可以拥有一个可以循环遍历一次的数组。
但即使使用这种反模式,您仍然可以做您需要的事情:
var items = cart.Zip(goods, (c,g) => new {Cart = c, Good = g}).Zip(price, (a, p) => new {Cart = a.Cart, Good = a.Good, Price = p});
var ticked = items.Where(i => i.Cart);
var message = string.Join(",", ticked.Select(t => t.Good));
var sum = ticked.Select(t => t.Price).Sum();
MessageBox.Show($"{message}\nTotal: {sum}");
这也可行,并且可能意味着更少的内存使用:
var ticked = cart.Select((value,index) => new {Cart = value, Price = price[index], Good = goods[index]})
.Where(i => i.Cart);
var message = string.Join(",", ticked.Select(s => s.Good));
var sum = ticked.Select(s => s.Price).Sum();
MessageBox.Show($"{message}\nTotal: {sum}");
您还可以使用索引:
int sum = 0;
var message = new StringBuilder();
var delimiter = "";
for(int i = 0; i<cart.Length; i++)
{
if (cart[i])
{
sum += price[i];
message.Append(delimiter).Append(goods[i]);
delimiter = ",";
}
}
MessageBox.Show($"{message}\nTotal: {sum}");
在这种情况下,index 选项可能更快,而且理解 linq 选项也不再困难(尽管它通常是相反的方式),即使它的代码更多。
关于c# - 遍历数组,将值相互绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53340410/