2015-09-11 24 views
1

如何查找ListBox中元素的总和。我只需要找到一种方法来存储列表框和输出的值的总和,一旦用户插入错误的输入如何在WPF中找到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()); 

     } 
+0

你是什么意思是“当用户输入任何内容,但数字应用程序显示目前输入的项目的总和” –

+0

是不是像我已经添加文字124E,它应该显示我7? –

+0

你在这里得到错误吗? –

回答

1

这个工作对我来说,试试这个:

private void YesButton_Click(object sender, RoutedEventArgs e) 
    { 
     int sum = 0; 
     int i = 0; 
     // 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 
    { 
     sum = MyListBox.Items.Cast<int>().Sum(x => Convert.ToInt32(x)); 
     MessageBox.Show("Sum is: " +sum); 
    } 
    // Clear InputBox. 
    InputTextBox.Text = String.Empty; 
} 
+0

非常感谢你! – progx

+0

乐于帮助! –

+0

@Nikita当他将整数值添加到列表框中时,我们不需要我之前提到的演员('演员和选择(x =>转换.ToInt32(x))''),并且它足够'铸造就像我在下面的答案中所做的一样。你可能会发现它有帮助:) –

3

你的代码的问题是在这里:

MyListBox.Items.Cast<ListBoxItem> 

要计算您的列表框中的项目的总和,如果你确信它们是添加为int或字符串整数,你可以使用这个片段:

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

上面的代码假定您将项目添加到列表框全光照g这样的代码:

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; 
+0

我做了你的建议,但仍然无法正常工作... – progx

+0

@programadorxpert请发布更新代码,然后我会检查它:)这里工作正常。 –

+0

我发布了一个更清晰的编辑到@ RezaAghaei的上面的代码片段,但基本上,它应该工作。它应该替换你的'else'块的全部内容。 – dexterlo

相关问题