Let’s assume we have a list of CampaignInfoData objects that have one property named NumberOfBatches of type int.
private List<CampaignInfoData> m_campaignInfosList = new List<CampaignInfoData>();
Using the Max method, we can get the largest number of batches in one campaign:
int largestNumberOfBatches = m_campaignInfosList.Max( f => f.NumberOfBatches );
but what I wanted was to get the campaign object with the largest number of batches. To get that, we can use the Aggregate method:
CampaignInfoData largestCampaign = m_campaignInfosList.Aggregate( ( seed, f ) => f.NumberOfBatches > seed.NumberOfBatches ? f : seed );
The Aggregate method accepts a lambda expression with two parameters. The first parameter holds the result of the previous lambda function execution, and the second is the current item on the list at a specific point in time.
The method traverses the list from beginning to end, and for each element, executes the code to the right of the => symbol on the lambda expression. After that, it puts the result value on the first parameter (seed) and moves to the next element on the list.
When it reaches the last element, the Aggregate method returns the result of the last lambda function execution.