c# 常见的取中值(去掉最大值,最小值,剩下的值求平均)
public object Getmedianaverage(int number, DateTime startdate, DateTime enddate) { #region 中值平均 number = 5; string sql = string.Format("SELECT ID,DEEP_DISPLACEMENT_X_VALUE,ACQUISITION_DATETIME FROM [dbo].[T_THEMES_DEFORMATION_DEEP_DISPLACEMENT] WHERE ACQUISITION_DATETIME BETWEEN '{0}' AND '{1}' ", "2020-05-15 10:55:13", "2020-05-15 20:55:13"); DataTable Datalist = SqlHelper.ExecuteDataSetText(sql, null).Tables[0]; List<Medianaavg> oldMedianaavg = new List<Medianaavg>(); // 原数组 foreach (DataRow item in Datalist.Rows) { Medianaavg avginfo = new Medianaavg(); avginfo.id = int.Parse(item["ID"].ToString()); avginfo.value = double.Parse(item["DEEP_DISPLACEMENT_X_VALUE"].ToString()); avginfo.date = DateTime.Parse(item["ACQUISITION_DATETIME"].ToString()); oldMedianaavg.Add(avginfo); } //新数组 List<NewMedianaavg> NewMedianaavg = new List<NewMedianaavg>(); foreach (var index in oldMedianaavg) { NewMedianaavg Newinfo = new NewMedianaavg(); Newinfo.id = index.id; Newinfo.value = index.value; Newinfo.date = index.date; NewMedianaavg.Add(Newinfo); } List<Beforeorder> orderlist = new List<Beforeorder>(); int c = 0; for (int i = 0; i <oldMedianaavg.Count; i++) { //排序前添加 for (int a = 0 +c; a < number +c; a++) { Beforeorder orderinfo = new Beforeorder(); orderinfo.id = oldMedianaavg[a].id; orderinfo.value = oldMedianaavg[a].value; orderinfo.date = oldMedianaavg[a].date; orderlist.Add(orderinfo); } //排序计算 var query = from items in orderlist orderby items.value select items; List<afterorder> afterorderlist = new List<afterorder>(); //满足传过来条件,排序后 放入数据的临时数组 //排序后的值添加到数组 foreach (var item in query) { afterorder afterinfo = new afterorder(); afterinfo.id = item.id; afterinfo.value = item.value; afterinfo.date = item.date; afterorderlist.Add(afterinfo); } //去掉最小值 afterorderlist.RemoveAt(afterorderlist.Count - (afterorderlist.Count)); // 去掉最大值 afterorderlist.RemoveAt(afterorderlist.Count - 1); double aftersum = 0.0; double afteravg = 0.0; for (int d = 0; d < afterorderlist.Count; d++) { aftersum += afterorderlist[d].value; } afteravg = Math.Round(Math.Round(aftersum, 6) / afterorderlist.Count,6); if (number + c < NewMedianaavg.Count) { NewMedianaavg[number + c].value = afteravg; } //清空 orderlist = new List<Beforeorder>(); //清空排序后的数组使一直保存五条数据 afterorderlist = new List<afterorder>(); c++; } MedianaavgCollection collection = new MedianaavgCollection(); collection.oldMediandata = oldMedianaavg; collection.newMediandata = NewMedianaavg; return collection; #endregion }