Performing Calculations in LINQ Query: Part 10

This is tenth part of the "LINQ" series of articles that I have started from here. In the last article you learned how to transform source data or objects into a XML file and this article will teach how to perform some calculations in a LINQ query.


Let's assume we have the following data in a data source:


linq-query.png


And we want to determine the Product's Total Price by multiplying UnitPrice and UnitInStock data. So, what would be the LINQ query to evaluate the 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 preceding underlined query, you will see that a multiplication is performed on the two columns UnitPrice and UnitInStock. Once we get the result it will be converted to a string and then it will be assigned to the ProductTotalPrice variable. So, we have ProductName and ProductTotalPrice in the query that will be executed in a foreach loop to get the 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 the 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 the calculated information from a LINQ query too.
 

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


Similar Articles