Skip to main content
 首页 » 编程设计

c#之根据每个列表项的 bool 值添加或减去一个值

2024年02月06日12JeffreyZhao


好吧,我会解释我想做什么。
我有一个购买者列表和一个列表框。当我将购买者添加到列表框时,他也被添加到名为 Purchasers 的列表中。在此列表中,我有一个购买者姓名的值和一个表示他是否付款的 bool 值。查看我的列表和它的类:

public class Purchaser 
{ 
     public string Name { get; set; } 
     public bool Paid { get; set; } 
} 
 
List<Purchaser> Purchasers = new List<Purchaser>(); 

现在我将解释我打算做什么:所有购买者必须支付 5 美元。我有一个名为 box_Paid 的复选框,当我选中或取消选中它时,变量 paid 会针对列表框中实际选定的购买者变为真或假。
我在列表框中为购买者设置了一个限制:总共 14 个,一个名为 label_AmountLeft 的标签中的值为 70 美元。
70/14 = 5 美元。每个购买者需要支付 5 美元。我现在需要的是,当我使用 box_Paid.CheckedChanged 事件为确定购买者转换变量时,值为 70 的标签减少 5 个单位。例如,当在列表框中选择了采购员 Tom 时,我选中了我的复选框。 Tom 的变量 paid 值现在将为 true 并且 label_AmountLeft 的值现在将为 65。我现在检查 Dylan,值变为到 60。如果我取消选中 Tom 的文本框,值将变为 65,因为 Dylan 的变量 paid 是 true。如果我取消选中两个购买者的复选框,变量将为 false 并且 label_AmountLeft 值将返回到 70。
我正在尝试使用:

double a, b = 5, rest; 
private void box_Paid_CheckedChanged(object sender, EventArgs e) 
{ 
    if (box_Paid.Checked == true) 
    { 
        Purchaser p = Purchasers[listDOF.SelectedIndex]; 
        p.Paid = true; 
        a = System.Convert.ToDouble(label_AmountLeft.Text); 
        rest = a - b; 
        label_AmountLeft.Text = System.Convert.ToString(rest); 
    } 
    else 
    { 
        Purchaser p = Purchasers[listDOF.SelectedIndex]; 
        p.Paid = false; 
        a = System.Convert.ToDouble(label_AmountLeft.Text); 
        rest = a + b; 
        label_AmountLeft.Text = System.Convert.ToString(rest); 
    } 
} 

但这不起作用。我认为这个问题很难理解,但我希望有人能够帮助我。提前致谢!

请您参考如下方法:

如果您正确地更新了您的列表,那么可以简单地使用以下方法计算总和:

var sum = Purchasers.Where(p => p.Paid).Count() * 5; 

或者,您可以为总和设置一个单独的字段,以避免每次都解析文本框值:

// oh, and btw, don't use double when working with money 
private decimal _sum; 
private void box_Paid_CheckedChanged(object sender, EventArgs e) 
{ 
    if (box_Paid.Checked == true) 
    { 
        _sum += 5; 
    } 
    else 
    { 
        _sum -= 5; 
    } 
 
    label_AmountLeft.Text = _sum.ToString(); 
} 

但奇怪的是,您根本没有更新原始列表中的项目,而是每次都创建新的 Purchaser 实例(从事件处理程序返回后立即收集这些实例).

所以,我猜代码应该是这样的:

private void box_Paid_CheckedChanged(object sender, EventArgs e) 
{  
    // get the currently selected item 
    var selectedPurchaser = Purchasers[listDOF.SelectedIndex]; 
 
    // set its state 
    selectedPurchaser.Paid = box_Paid.Checked; 
 
    // calculate the sum and display it 
    UpdateSum(); 
} 
 
private void UpdateSum() 
{ 
    // calculate the paid sum 
    var paidSum = Purchasers.Where(x => x.Paid).Count() * 5; 
 
    // get the amount left 
    var amountLeft = 70 - paidSum; 
 
    // update the text box (using whatever formatting you prefer) 
    label_AmountLeft.Text = string.Format("${0:0.00}", amountLeft); 
}