diff --git a/Falcon.SugarApi.Test/IEnumerableExtendTest.cs b/Falcon.SugarApi.Test/IEnumerableExtendTest.cs index 7f7cd7a..f491e38 100644 --- a/Falcon.SugarApi.Test/IEnumerableExtendTest.cs +++ b/Falcon.SugarApi.Test/IEnumerableExtendTest.cs @@ -77,6 +77,36 @@ namespace Falcon.SugarApi.Test } + + [TestMethod("Reduce测试")] + public void ReduceTest() { + var list = new List { 1, 2, 3, 4 }; + var sum = list.Reduce((a, b) => a + b, 0); + Assert.IsTrue(sum == 10, "对数组求和错误"); + + var people = new List { + new person{ IsMan=true,age=30 }, + new person{ IsMan=false,age=40 }, + new person{ IsMan=true,age=50 }, + new person{ IsMan=true,age=60 }, + }; + var sumage = people.Reduce((a, b) => a + (b.IsMan ? b.age : 0), 0); + Assert.IsTrue(sumage == 30 + 50 + 60, "有条件求和错误"); + + var men = people.Reduce((a, b) => { + if (b.IsMan) { + a.Add(b); + } + return a; + }, new List()); + foreach (var p in men) { + Assert.IsTrue(p.IsMan, "缩减为男性集合错误!"); + } + + var arr = new string[] { }; + var initVal = arr.Reduce((a, b) => throw new Exception("空集合不可以调用缩减方法"), "abc"); + Assert.IsTrue(initVal == "abc", "空集合返回初始值,并且不调用缩减方法。"); + } } internal class ToDataTableTestModel @@ -85,5 +115,11 @@ namespace Falcon.SugarApi.Test public string Name { get; set; } } + internal class person + { + public int age { get; set; } + public bool IsMan { get; set; } + } + } diff --git a/Falcon.SugarApi/IEnumerableExtend.cs b/Falcon.SugarApi/IEnumerableExtend.cs index 3011029..5d92872 100644 --- a/Falcon.SugarApi/IEnumerableExtend.cs +++ b/Falcon.SugarApi/IEnumerableExtend.cs @@ -84,5 +84,25 @@ namespace Falcon.SugarApi } return dt; } + + /// + /// 对枚举进行缩减,并返回缩减后的结果。 + /// + /// 枚举的类型 + /// 缩减结果类型 + /// 原枚举 + /// 缩减方法 + /// 缩减初始值 + /// 缩减结果 + public static TR Reduce(this IEnumerable source, Func reduceFunc, TR initialValue) { + if (reduceFunc == null) { + throw new ArgumentNullException(nameof(reduceFunc)); + } + var result = initialValue; + foreach (var i in source) { + result = reduceFunc(result, i); + } + return result; + } } }