Performing Calculations in LINQ Query - Part 10

This is tenth part of the ‘LINQ’ series posts that I have started from here. In the last post you learnt how to transform source data/object into XML file and in this post will go ahead and learn how to perform some calculations in LINQ query.

Let’s assume we have following data in data source:


And we want to find-out Product’s Total Price by multiplying UnitPrice and UnitInStock data. So, what would be the LINQ query to find the calculated data?

Let’s write a query to solve this:

var query = from std in DNDC.Products
            where std.SupplierID == 1
            select new { ProductName = std.ProductName, ProductTotalPrice = String.Format("Total Price = {0}", (std.UnitPrice) * (std.UnitsInStock)) };

To understand it, look at the above underlined query, you will find multiplication is being done on two different columns that is on UnitPrice and UnitInStock. Once we get the multiplied value that will be casted as string equivalent data and then will assign this to ProductTotalPrice variable. So, we have ProductName and ProductTotalPrice in query that will be executed in foreach loop to get entire data as given below:

foreach (var q in query)
{
    Console.WriteLine("Product Name: " + q.ProductName + ", Total Price: " + q.ProductTotalPrice + "");
}

When you execute above loop, you will get following output:

Product Name: Chai, Total Price: Total Price = 702.000000
Product Name: Chang, Total Price: Total Price = 323.000000
Product Name: Aniseed Syrup, Total Price: Total Price = 130.000000

So, using this way you can find calculated information from LINQ query too.

I hope you will find it useful. Thanks for reading.

Comments

  1. thanks you provided the anser to my problem

    ReplyDelete

Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System