Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please consider this example,

List<int> lst = new List<int> { 1, 2, 3, 4 };
int result = lst.Aggregate((x, y) => x * y);


As per the articles (x,y) specifies input parameters and x*y as implementation, my doubt is, aggregate() is the method of list, then it has to have inner implementation of aggregation by its own, then what (x*y) specifies or rather needed here...

Please mention the articles explaining lambda and list separately...

Thanks in advance,
Posted

Here x * y indicates that the elements will be aggregated by multiplication.

Refer - C# Aggregate[^].
See the examples and their outputs. You will be clear.
Quote:

C#
int[] array = { 1, 2, 3, 4, 5 };
	int result = array.Aggregate((a, b) => b + a);
	// 1 + 2 = 3
	// 3 + 3 = 6
	// 6 + 4 = 10
	// 10 + 5 = 15
	Console.WriteLine(result);

	result = array.Aggregate((a, b) => b * a);
	// 1 * 2 = 2
	// 2 * 3 = 6
	// 6 * 4 = 24
	// 24 * 5 = 120
	Console.WriteLine(result);
 
Share this answer
 
Comments
Chaitanya Pai 17-Jul-13 4:51am    
Thanks for the reply. Why cant i pass (a => a>2), why only (a,b)...
Aggregate function will work on two elements at a time. That's why. And I guess you are now clear after referring to the answer by OriginalGriff...
A lambda is pretty much just a method without a name. The (x,y) part before the => specifies the parameters and the x * y part after it is the body of the function.
In this case, what you are doing is the equivalent of:
C#
List<int> lst = new List<int> { 1, 2, 3, 4 };
int x = 0;
for (int i = 0; i < lst.Count; i ++)
    {
    int y = lst[i];
    x = i == 0 ? y : x * y;
    }
int result = x;
Only with deferred execution (don't worry about that for the moment).

[edit]Spurious HTML closing tags removed - OriginalGriff[/edit]
 
Share this answer
 
v2
Comments
Chaitanya Pai 17-Jul-13 5:08am    
Got it thanks.. :)
OriginalGriff 17-Jul-13 6:10am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900