如何在WPF

时间:2015-09-11 05:45:21

标签: c# wpf listbox

如何在ListBox中找到元素的总和。我只需要找到一种方法来存储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());

        }

2 个答案:

答案 0 :(得分:3)

您的代码存在问题:

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;

答案 1 :(得分: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;
}