Skip to main content
 首页 » 编程设计

c#之如何在 WPF 的 ListBox 中找到元素的总和

2024年02月05日10lonelyxmas

如何找到列表框中元素的总和。我只需要找到一种方法来存储 ListBox 的值之和,并在用户插入错误输入时输出

 private void theMethod(object sender, RoutedEventArgs e) 
     { 
 
 
        // YesButton Clicked! Let's hide our InputBox and handle the input text. 
        InputBox.Visibility = System.Windows.Visibility.Collapsed; 
 
        // Do something with the Input 
        String input = InputTextBox.Text; 
        int result = 0; 
        if (int.TryParse(input, out result)) 
        { 
            MyListBox.Items.Add(result); // Add Input to our ListBox. 
        } 
        else { 
            String[]arr = new String[3]; 
            // I just want to be able to output the sum of the elements of the ListBox (MyListBox) 
            for ( i = 0; i < MyListBox.Items.Count; i++) 
            { 
              //MyListBox.Items[i].ToString(); 
 
                MyListBox.Items.Cast<ListBoxItem>().Sum(x => Convert.ToInt32(x)).ToString(); 
 
            } 
             sum.ToString(); 
             MessageBox.Show("Sum is: " +MyListBox.Items.Cast<ListBoxItem>().Sum(x => Convert.ToInt32(x)).ToString()); 
 
        } 

请您参考如下方法:

你的代码的问题在这里:

MyListBox.Items.Cast<ListBoxItem> 

要计算列表框中项目的总和,如果您确定它们是作为 int 或 string 添加的整数,则可以使用此代码段:

var sum= this.ListBox1.Items.Cast<object>() 
    .Select(x => Convert.ToInt32(x)) 
    .Sum(); 
MessageBox.Show(sum.ToString()); 

上面的代码假定您使用这样的代码将项目添加到 ListBox:

var value= this.TextBox1.text; 
//your logic for null checking and ... 
this.ListBox1.Items.Add(value); 

这是我根据你的代码测试的完整代码。

当您向列表框添加整数值时,我们不需要 Cast<object>和 Select(x=>Convert.ToInt32(x))已经足够了 Cast<int>如下所示:

String input = InputTextBox.Text; 
int result = 0; 
if (int.TryParse(input, out result)) 
{ 
    MyListBox.Items.Add(result); 
} 
else 
{ 
    var sum = this.MyListBox.Items.Cast<int>().Sum(); 
    MessageBox.Show(string.Format("Sum is: {0}", sum)); 
    sum.ToString(); 
} 
InputTextBox.Text = String.Empty;