List<int> Loc=new List<int>(); //假设panel中有4个PictureBox foreach (Control c in pl.Controls) { if (c is PictureBox && c.Name !="pBx_bjl") { Loc.Add(c.Location.X); }} Loc.Sort();// // Loc[0]就是最小的,Loc已经排序了,你就知道怎么处理了吧
//首先要創建一個實現ICompare的類,用來排序 public class PictureBoxComparer : IComparer<PictureBox> { #region IComparer<PictureBox> 成员 public int Compare(PictureBox x, PictureBox y) { if (x.Location.X > y.Location.X) return 1; else if (x.Location.X < y.Location.X) return -1; else { return 0; } } #endregion } //下面是使用list存儲並排序及取值的代碼 List<PictureBox> list=new List<PictureBox>(); foreach (Control c in panel1.Controls) { if (c is PictureBox) { list.Add((PictureBox) c); } } //下面代碼是對list進行排序,會以升序來排列。 list.Sort((IComparer<PictureBox>)new PictureBoxComparer()); //下面的代碼可以枚舉所有的pictureBox foreach (PictureBox pic in list) { MessageBox.Show(pic.Location.X.ToString()); } //獲取最大的X值的 PictureBox MaxXPicBox = list[list.Count - 1]; //獲取最小的X值的 PictureBox MinXPicBox = list[0];
public class PictureBoxComparer : IComparer { #region IComparer 成员 public int Compare(object x, object y) { PictureBox picX = (PictureBox)x; PictureBox picY = (PictureBox) y; if (picX.Location.X > picY.Location.X) return 1; else if (picX.Location.X < picY.Location.X) return -1; else { return 0; } } #endregion } ArrayList list = new ArrayList(); foreach (Control c in panel1.Controls) { if (c is PictureBox) { list.Add(c); } } //下面代碼是對list進行排序,會以升序來排列。 list.Sort((IComparer)new PictureBoxComparer()); //下面的代碼可以枚舉所有的pictureBox for (int i = 0; i < list.Count;i++ ) { PictureBox pic = (PictureBox)list[i]; MessageBox.Show(pic.Location.X.ToString()); } //獲取最大的X值的 PictureBox MaxXPicBox = (PictureBox) list[list.Count - 1]; //獲取最小的X值的 PictureBox MinXPicBox = (PictureBox)list[0];