新增对IEnumerable对象的Reduce可以先提供初始值后提供缩减方法的重载
This commit is contained in:
parent
ca1209c310
commit
ce77072812
|
@ -83,6 +83,8 @@ namespace Falcon.SugarApi.Test
|
|||
var list = new List<int> { 1,2,3,4 };
|
||||
var sum = list.Reduce((a,b) => a + b,0);
|
||||
Assert.IsTrue(sum == 10,"对数组求和错误");
|
||||
sum = list.Reduce(0,(a,b) => a + b);
|
||||
Assert.IsTrue(sum == 10,"对数组求和错误");
|
||||
|
||||
var people = new List<person> {
|
||||
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);
|
||||
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) => {
|
||||
if(b.IsMan) {
|
||||
|
@ -102,6 +106,15 @@ namespace Falcon.SugarApi.Test
|
|||
foreach(var p in men) {
|
||||
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 initVal = arr.Reduce((a,b) => throw new Exception("空集合不可以调用缩减方法"),"abc");
|
||||
|
|
|
@ -41,8 +41,7 @@ namespace Falcon.SugarApi
|
|||
var val = p.GetValue(i);
|
||||
try {
|
||||
row[p.Name] = val;
|
||||
}
|
||||
catch (Exception ex) {
|
||||
} catch(Exception ex) {
|
||||
throw new Exception($"值设置失败!{p.Name}:{val}",ex);
|
||||
}
|
||||
}
|
||||
|
@ -104,5 +103,25 @@ namespace Falcon.SugarApi
|
|||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user