Create aggregate function using lambda expressions on collectionView in C#

Hope you need this article for updating your skills. As we seen in the last article, we learned about collection view and how to create filters using them. If you miss just take a look at it. To I will help you learn som lambda expression

Lambda experession ?

Lambda expressions permit the creation of anonymous functions with a very concise syntax. I don’t want explain what lambda expression is , I will show you how to use it. For learn more about lambda please visit Richard Carr’s lackwaspBlog ,he had a detailed guide to lambda.

The following is an example of lambda expression.

(params) => expression

let’s jump into the regular salesinformation example. The sales Collection used to store all sales information such as Customer,Date,Amount,tax,discount etc. It may contain many of them, that is why we used collection or List.

We are going to use Agrgregate feature of collectionview object to create lambda function, for find total sale amount ,tax collected etc

 var total_saleAmount = Salescolletionview.Cast<SalesView>()
.Aggregate<SalesView, double>(0, (totalSale, s) => totalSales += s.Amount);

The SaleCollectionView class Hold information about Sales which is in the type of ViewClass. So first up all we can cast the view to SalesView and then invoke Aggregate. The Aggregate functionality of C#.Net let us create anonymous function using lambda expression.

At first we had initialise the output variable and access the Amount property of viewclass and then add it up.

In the similar manner you can operate on other properties of view class.

 var total_tax = Salescolletionview.Cast<SalesView>().
Aggregate<SalesView, double>(0, (tax, s) => tax+= s.Tax);

Published by


A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

One thought on “Create aggregate function using lambda expressions on collectionView in C#”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.