新增对IEnumerable对象的Reduce可以先提供初始值后提供缩减方法的重载

This commit is contained in:
falcon 2022-12-07 10:36:42 +08:00
parent ca1209c310
commit ce77072812
2 changed files with 67 additions and 35 deletions

View File

@ -83,6 +83,8 @@ namespace Falcon.SugarApi.Test
var list = new List<int> { 1,2,3,4 }; var list = new List<int> { 1,2,3,4 };
var sum = list.Reduce((a,b) => a + b,0); var sum = list.Reduce((a,b) => a + b,0);
Assert.IsTrue(sum == 10,"对数组求和错误"); Assert.IsTrue(sum == 10,"对数组求和错误");
sum = list.Reduce(0,(a,b) => a + b);
Assert.IsTrue(sum == 10,"对数组求和错误");
var people = new List<person> { var people = new List<person> {
new person{ IsMan=true,age=30 }, new person{ IsMan=true,age=30 },
@ -92,6 +94,8 @@ namespace Falcon.SugarApi.Test
}; };
var sumage = people.Reduce((a,b) => a + (b.IsMan ? b.age : 0),0); var sumage = people.Reduce((a,b) => a + (b.IsMan ? b.age : 0),0);
Assert.IsTrue(sumage == 30 + 50 + 60,"有条件求和错误"); Assert.IsTrue(sumage == 30 + 50 + 60,"有条件求和错误");
sumage = people.Reduce(0,(a,b) => b.IsMan ? a + b.age : a);
Assert.IsTrue(sumage == 30 + 50 + 60,"有条件求和错误");
var men = people.Reduce((a,b) => { var men = people.Reduce((a,b) => {
if(b.IsMan) { if(b.IsMan) {
@ -102,6 +106,15 @@ namespace Falcon.SugarApi.Test
foreach(var p in men) { foreach(var p in men) {
Assert.IsTrue(p.IsMan,"缩减为男性集合错误!"); Assert.IsTrue(p.IsMan,"缩减为男性集合错误!");
} }
men = people.Reduce(new List<person>(),(a,b) => {
if(b.IsMan) {
a.Add(b);
}
return a;
});
foreach(var p in men) {
Assert.IsTrue(p.IsMan,"缩减为男性集合错误!");
}
var arr = new string[] { }; var arr = new string[] { };
var initVal = arr.Reduce((a,b) => throw new Exception("空集合不可以调用缩减方法"),"abc"); var initVal = arr.Reduce((a,b) => throw new Exception("空集合不可以调用缩减方法"),"abc");

View File

@ -41,8 +41,7 @@ namespace Falcon.SugarApi
var val = p.GetValue(i); var val = p.GetValue(i);
try { try {
row[p.Name] = val; row[p.Name] = val;
} } catch(Exception ex) {
catch (Exception ex) {
throw new Exception($"值设置失败!{p.Name}:{val}",ex); throw new Exception($"值设置失败!{p.Name}:{val}",ex);
} }
} }
@ -104,5 +103,25 @@ namespace Falcon.SugarApi
} }
return result; return result;
} }
/// <summary>
/// 对枚举进行缩减,并返回缩减后的结果。
/// </summary>
/// <typeparam name="T">枚举的类型</typeparam>
/// <typeparam name="TR">缩减结果类型</typeparam>
/// <param name="source">原枚举</param>
/// <param name="reduceFunc">缩减方法</param>
/// <param name="initialValue">缩减初始值</param>
/// <returns>缩减结果</returns>
public static TR Reduce<T, TR>(this IEnumerable<T> source,TR initialValue,Func<TR,T,TR> reduceFunc) {
if(reduceFunc == null) {
throw new ArgumentNullException(nameof(reduceFunc));
}
var result = initialValue;
foreach(var i in source) {
result = reduceFunc(result,i);
}
return result;
}
} }
} }