对枚举和数组增加缩减Reduce方法

This commit is contained in:
falcon 2022-10-27 14:32:38 +08:00
parent a8c13892dc
commit d49a382aab
2 changed files with 56 additions and 0 deletions

View File

@ -77,6 +77,36 @@ namespace Falcon.SugarApi.Test
}
[TestMethod("Reduce测试")]
public void ReduceTest() {
var list = new List<int> { 1, 2, 3, 4 };
var sum = list.Reduce((a, b) => a + b, 0);
Assert.IsTrue(sum == 10, "对数组求和错误");
var people = new List<person> {
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<person>());
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; }
}
}

View File

@ -84,5 +84,25 @@ namespace Falcon.SugarApi
}
return dt;
}
/// <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, Func<TR, T, TR> 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;
}
}
}