我的程序将坐标(double x,douule y)读入ListBox,需要在使用SelectedIndices和MultiExtended选择它们后计算它们的平均值。 问题是如何使用每个Multiselection刷新我的代码。 如您所见,我将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();
}
答案 0 :(得分: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);
答案 1 :(得分: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();
}