1

我的程序将坐标(double x,douule y) 读取到 ListBox 中,并且需要在使用 SelectedIndices 和 MultiExtended 选择它们后计算它们的平均值。问题是如何用每个多选刷新我的代码。如您所见,我将 SelectedIndices[0] 默认设置为 0。目前,我的程序只是将第一个坐标除以 selectedIndices 的数量进行平均。

如果您考虑任何改进我的代码的方法,我也想知道。

谢谢!

   private void button3_Click(object sender, EventArgs e)//Average
    {
        int[] selected = new int[] {points_List.SelectedIndices[0] };
        double sumX = 0, sumY = 0; ;
        foreach (int iIndex in selected)
        {
            sumX += points[iIndex].X;
            sumY += points[iIndex].Y;
        }
        averageX = (sumX) / (points_List.SelectedIndices.Count);
        averageY = (sumY) / (points_List.SelectedIndices.Count);
        label1.Text = "Average is: ";
        label1.Text += averageX.ToString();
        label1.Text += "   ";
        label1.Text += averageY.ToString();
    }
4

2 回答 2

1

正确的代码将需要SelectedIndices通过OfType<T>Cast<T>。此外,调用ToArray具体化结果以避免必须计算两次也很方便。

var selectedPoints = points_List.SelectedIndices.
    OfType<int>().
    Select(i => points[i]).
    ToArray();
var averageX = selectedPoints.Average(p => p.X);
var averageY = selectedPoints.Average(p => p.Y);
于 2013-01-01T23:46:30.800 回答
0

最终解决方案,谢谢大家。

        {
        double averageX = 0, averageY = 0;
        var selectedPoints = from int i in pointsList.SelectedIndices select points[i];
        if (pointsList.SelectedIndices.Count == 0)
        {
            label1.Text = "Average is 0.000 0.000 ";//default text
            return;
        }
        averageX = selectedPoints.Average(p => p.X);
        averageY = selectedPoints.Average(p => p.Y);
        label1.Text = "Average X: ";
        label1.Text += averageX.ToString();
        label1.Text += "   Y:";
        label1.Text += averageY.ToString();
    }
于 2013-01-03T21:22:08.097 回答