c#扩展方法奇思妙用高级篇二:Aggregate扩展其改进2010-04-23 博客园 鹤冲天Enumerable.Aggregate 扩展方法在System.Linq命名空间中,是Enumerable类的第一个方法(按字母顺序排名),但确是Enumerable里面相对复杂的方法。MSDN对它的说明是:对序列应用累加器函数。备注中还有一些说明,大意是这个方法比较复杂,一般情况下用Sum、Max、Min、Average就可以了。看看下面的代码,有了Sum,谁还会用Aggregate呢!
public static void Test1()
{
int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum1 = nums.Sum();
int sum2 = nums.Aggregate((i,j)=>i+j);
}
同是求和,Sum不再需要额外参数,而Aggregate确还要将一个lambda作为参数。因为用起来麻烦,操作太低级,Aggregate渐渐被大多人忽视了...实际上Aggregate因为“低级”,功能确是很强大的,通过它可以简化很多聚合运算。首先来看对Aggregate组装字符串的问题:
public static void Test2()
{
string[] words = new string[] { "Able", "was", "I", "ere", "I", "saw", "Elba"};
string s = words.Aggregate((a, n) => a + " " + n);
Console.WriteLine(s);
}
输出结果是:Able was I ere I saw Elba (注:出自《大国崛起》,狄娜最后讲述了拿破仑一句经典)。当然考虑性能的话还是用StringBuilder吧,这里主要介绍用法。这个Sum做不到吧!Aggregate还可以将所有字符串倒序累加,配合String.Reverse扩展可以实现整个句子的倒序输出:
public static void Test3()
{
string[] words = new string[] { "Able", "was", "I", "ere", "I", "saw", "Elba"};
string normal = words.Aggregate((a, n) => a + " " + n);
string reverse = words.Aggregate((a, n) => n.Reverse() + " " + a);
Console.WriteLine("正常:" + normal);
Console.WriteLine("倒置:" + reverse);
}
// 倒置字符串,输入"abcd123",返回"321dcba"
public static string Reverse(this string value)
{
char[] input = value.ToCharArray();
char[] output = new char[value.Length];
for (int i = 0; i < input.Length; i++)
output[input.Length - 1 - i] = input[i];
return new string(output);
}
看下面,输出结果好像不太对:

怎么中间的都一样,两的单词首尾字母大小写发生转换了呢?!仔细看看吧,不是算法有问题,是输入“有问题”。搜索一下“Able was I ere I saw Elba”,这可是很有名的英文句子噢!Aggregate还可以实现异或(^)操作:
public static void Test4()
{
byte[] data = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35 };
byte checkSum = data.Aggregate((a, n) => (byte)(a ^ n));
}
对经常作串口通信的朋友比较实用。