From d49a382aab365beeb9199f79082b24f8feac5831 Mon Sep 17 00:00:00 2001 From: falcon <9504402@qq.com> Date: Thu, 27 Oct 2022 14:32:38 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AF=B9=E6=9E=9A=E4=B8=BE=E5=92=8C=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E5=A2=9E=E5=8A=A0=E7=BC=A9=E5=87=8FReduce=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Falcon.SugarApi.Test/IEnumerableExtendTest.cs | 36 +++++++++++++++++++ Falcon.SugarApi/IEnumerableExtend.cs | 20 +++++++++++ 2 files changed, 56 insertions(+) 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; + } } }