👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
Using LINQ For Each to iterate Collections

Using LINQ For Each to iterate Collections

linq

26 Articles

Improve

In this article, let's learn about how to use ForEach in LINQ in .NET.

Note: If you have not done so already, I recommend you read the article on Using LINQ Count Min Max Average and Sum to Aggregate data.

Table of Contents

  1. Introduction
  2. Using LINQ For Each to iterate collections
  3. Using Sub Query in For Each
  4. Using Custom Method in For Each
  5. Summary

Introduction

When working with collection, we can perform set operation in them using LINQ ForEach() method. A set operation that iterates over an entire collection and allows us to set a property value within that collection. This is similar to a SQL UPDATE command.

LINQ ForEach() is used to answer questions about collection such as

  • Calculate a line total or set the total sales for a product.
  • Printing each element to the console.
  • Updating a property of each object in the collection.

Using LINQ For Each to iterate collections

Set operation can be done using ForEach with quert syntaz or method syntax. In a real-world scenario, you may want to calculate Total Stock Value of items in inventory. We can use query syntax to assign values to a property within an object. This can be done using a temporary variable, like let tmp, and then assigning the property value you want to update. For instance, let tmp = product.TotalStockValue = product.Price * product.Quantity sets the length of a product name.

Using the method syntax, you can use the ForEach method to directly set the property value of an object in a collection. For example, product.TotalStockValue = product.Price * product.Quantity assigns the length of the product name to another property within the product object.

Code Sample - LINQ ForEach

Demo - LINQ ForEach Demo

Let's try LINQ ForEach with Objects

  • We have Product class with following properties - Id, Name
  • The tables is loaded with product collection.
  • The Key Expression here is the Product TotalStock. ForEach() will iterate Products and set / update values.
  • Click on ForEach Button to view the TotalStock in Product.
  • Click on reset to try other combination
Id Name Color Price Quantity Total Stock
1 Shirt Black 1000 1
2 Shirt Red 1500 2
3 Shirt Black 2000 3
4 Shirt Red 2500 4
5 Shirt Brown 3000 5
6 Shirt White 3500 6

Using Sub Query in For Each

we'll learn how to use a sub query to calculate the total sales for each product in our Product object. Our Product class has some typical properties like Name, Color, and Price, but we also have a couple of calculated properties, including TotalStock and TotalSales. TotalSales is marked as a nullable data type so that we can have either null or the total sales in there.

Code Sample - LINQ For Each with Sub Query

Demo - LINQ ForEach Sub Query

Let's try LINQ ForEach with Sub Query

  • We have Product class with following properties - Id, Name, Price, TotalSale
  • We have Sale class with following properties - Id, ProductId, Quantity
  • The tables are loaded with product and sale collection.
  • The Key Expression here is the Product TotalSale. ForEach() will iterate Products and query matching sale for the product and set / update values.
  • Click on ForEach With SubQuery Button to view the TotalSale in Product.
  • Click on reset to try other combination
Products
Id Name Price Total Sale
1 Shirt 1000
2 Shirt 1500
3 Shirt 2000
4 Shirt 2500
5 Shirt 3000
6 Shirt 3500
Sales
Sale Id Product Id Quantity
123 1 1
789 1 2
456 2 3

Using Custom Method in For Each

We can use alternative method of calculating the TotalSales property in the Product object. Rather than using a subquery, we can use a method that allows us to call a method inside the query. We then call the CalculateTotalSalesForProduct method, passing in the current product and the sales collection. This method returns a decimal value calculated by running the same sales.Where query as before. By breaking out the calculation into a separate method, we can use more complex logic if needed. The resulting collection is an IEnumerable of Products, which we can filter using the Where method to only include those products with a TotalSales greater than 0. Finally, we convert the resulting collection to a list and return it.

Code Sample - LINQ For Each with Custom Method

Demo - LINQ ForEach Custome Method

Let's try LINQ ForEach with Custom Method

  • We have Product class with following properties - Id, Name, Price, TotalSale
  • We have Sale class with following properties - Id, ProductId, Quantity
  • The tables are loaded with product and sale collection.
  • The Key Expression here is the Product TotalSale. ForEach() will iterate Products and query matching sale for the product and set / update values.
  • Click on ForEach With Custom Method Button to view the Products with TotalSale > 0.
  • Click on reset to try other combination
Products
Id Name Price Total Sale
1 Shirt 1000
2 Shirt 1500
3 Shirt 2000
4 Shirt 2500
5 Shirt 3000
6 Shirt 3500
Sales
Sale Id Product Id Quantity
123 1 1
789 1 2
456 2 3

Summary

In this article we learn't how to iterate collections using ForEach. This allows you to set / update values for objects inside collection. We also learnt how to use sub queries inside ForEach for performing set operations. By using sub queries, we can easily calculate aggregate values for a collection based on related data in another collection. Overall by using query syntax or the method syntax, you can assign values to properties within objects in a collection and make updates efficiently.

  • Linq
  • ForEach
  • Loop