protected bool CheckBase(List datas, int index, int count, int threshold, Func action, int offset = 10) where T : struct, IComparable { var range = datas.GetRange(index, count); var res = range.All(x => x.CompareTo((T)(dynamic)(threshold + offset)) <= 0 && x.CompareTo((T)(dynamic)(threshold - offset)) >= 0); return action(res); } protected bool CheckBase (List datas, int index, int count, List thresholds, Func action, int offset = 10) where T : struct, IComparable { var range = datas.GetRange(index, count); var res = range.Zip(thresholds, (data, threshold) => data.CompareTo((T)(dynamic)(threshold + offset)) <= 0 && data.CompareTo((T)(dynamic)(threshold - offset)) >= 0 ).All(x => x); return action(res); }
定义了两个泛型方法 CheckBase
第一个方法 CheckBase
该方法首先通过 datas.GetRange(index, count) 从传入的 datas 列表中获取指定索引和数量的子列表 range。然后使用 LINQ 方法 All() 遍历 range 中的每个元素 x,检查其是否在阈值范围内,即是否满足 (x.CompareTo((T)(dynamic)(threshold + offset)) <= 0 && x.CompareTo((T)(dynamic)(threshold - offset)) >= 0) 的条件。最后,将结果传递给传入的 action 委托进行处理,并返回结果。
第二个方法 CheckBase
这两个方法可以用于校验给定数据列表中的数据是否满足指定的阈值要求,并通过提供的委托进行结果处理。
示例
// 示例 1 - 使用 CheckBase(List datas, int index, int count, int threshold, Func action, int offset = 10) 方法 List dataList = new List { 5, 7, 9, 11, 13, 15 }; int startIndex = 0; int elementsCount = 4; int threshold = 10; int offset = 2; bool result1 = CheckBase(dataList, startIndex, elementsCount, threshold, (res) => { Console.WriteLine($"All elements in the range [{startIndex}-{startIndex + elementsCount - 1}] are within the threshold +/-{offset}: {res}"); return res; }, offset); // 输出: All elements in the range [0-3] are within the threshold +/-2: False // 示例 2 - 使用 CheckBase (List datas, int index, int count, List thresholds, Func action, int offset = 10) 方法 List dataValues = new List { 1.2, 1.4, 1.5, 1.8, 2.1 }; int startIndex2 = 1; int elementsCount2 = 3; List thresholds = new List { 1, 2, 3 }; int offset2 = 0; bool result2 = CheckBase(dataValues, startIndex2, elementsCount2, thresholds, (res) => { Console.WriteLine($"All elements in the range [{startIndex2}-{startIndex2 + elementsCount2 - 1}] are within the thresholds +/-{offset2}: {res}"); return res; }, offset2); // 输出: All elements in the range [1-3] are within the thresholds +/-0: False
猜你喜欢
网友评论
- 搜索
- 最新文章
- 热门文章