Func(Of T1, T2, TResult) 委托:http://msdn.microsoft.com/zh-cn/library/bb534647.aspx
MSDN的例子:
static void Main(string[] args)
{
string sentence = "the quick brown fox jumps over the lazy dog";
string[] words = sentence.Split(' ');
string reversed = words.Aggregate((x, y) =>y + " " + x);
Console.WriteLine(reversed);
Console.ReadKey();
}例子中的两个参数,x、y应该怎么解释啊,x可以看成是集合的每一个元素,那y呢?并没有说明 y += x 啊,也没有说明y是什么东西,怎么就能行呢?
MSDN的例子:
static void Main(string[] args)
{
string sentence = "the quick brown fox jumps over the lazy dog";
string[] words = sentence.Split(' ');
string reversed = words.Aggregate((x, y) =>y + " " + x);
Console.WriteLine(reversed);
Console.ReadKey();
}例子中的两个参数,x、y应该怎么解释啊,x可以看成是集合的每一个元素,那y呢?并没有说明 y += x 啊,也没有说明y是什么东西,怎么就能行呢?
x 和 y 都是委托(匿名函数)的参数,这里用的是lambda表达式。参数的类型根据推断确定。过程是迭代的,x:"the", y:"quick" => y+ " " + x: "quick the"
x: "quick the", y: "brown" => y+ " " + x: "brown quick the"
...
意思是说words中的元素之间的关系就是多了个空格连接了起来
1
2
4
3
====得到
1+2+4+3
看来直接
words.Aggregate((x, y) =>x + "+" + y);
就可以,我之前还每个记录又重新查询一次数据库。
while (enumerator.MoveNext()) //移动到下一个元素开始遍历
{
current = func(current, enumerator.Current);
}第一次遍历的时候将一个元素和第二元素的值当作回调函数的参数,将函数的操作结果返回并赋值给current第二次遍历的时候
用返回的结果和下一个元素继续调用函数。
用你的例子来分析
string sentence = "the quick brown fox jumps over the lazy dog";
string[] words = sentence.Split(' ');
string reversed = words.Aggregate((x, y) => y + " " + x);第一个调用
current = func("the", "quick"); //current得到的值为 "quick the"第二次调用
current = func("quick the", "brown"); //current得到的值为 "brown quick the"第三次调用
current = func("brown quick the", "fox"); //current得到的值为 "fox brown quick the"以此类推最后return current;返回这个结果,就是数组元素反过来了。
完整代码:public static TSource Aggregate<TSource>(this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (func == null)
{
throw Error.ArgumentNull("func");
}
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
if (!enumerator.MoveNext())
{
throw Error.NoElements();
}
TSource current = enumerator.Current;
while (enumerator.MoveNext())
{
current = func(current, enumerator.Current);
}
return current;
}
}
楼主应该把问题分开考虑,分成:
(x,y)=>y+" "+x
和
words.Aggregate();其中(x,y)=>y+" "+x是一个lambda表达式,此处可以转化为:
public string Method(string x,string y)
{
return y+" "+x;
}
也就是把两个字符串合并为一个字符串(第一个参数在前,第二个参数在后,并且中间加空格)的函数,这个函数谁用都可以,这里的x,y只是有象征意义.words.Aggregate()这是string[]类型提供的一个方法,这个方法的完成需要一个具体的操作,这里提供的操作就是上面lambda提供的函数。
这个方法的说明参考8楼。