Avoid Repeated Execution of LINQ Queries in C#

LINQ queries follow deferred execution. This means when you access a LINQ query, it will get executed. If not well designed, it will execute every time you access it. In order to avoid that, convert the result to a list and then do further operations on it.

The below query explains the difference:

int[] kidsAges = { 10, 8, 12, 14, 15, 16 };var youngTeens = kidsAges.Where(k = k  var youngTeensCount = youngTeens.Count();var youngTeensMaxAge = youngTeens.Max();

In the above example, the LINQ query is executed twice. To avoid this, do a .ToList()?on the LINQ Query and then use its result.

int[] kidsAges = { 10, 8, 12, 14, 15, 16 };var youngTeens = kidsAges.Where(k => k < 14).ToList();var youngTeensCount = youngTeens.Count();var youngTeensMaxAge = youngTeens.Max();
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

Interstitial Ads: Best Practices for Successful Campaigns

Interstitial Ads: Best Practices for Successful Campaigns

Interstitial Ads: Best Practices for Successful Campaigns Interstitial ads are full-screen advertisements that appear to grasp the attention of on-site prospects, creating opportunities for brands seeking effective ways to communicate their proposition of value. With such an attention-grabbing format and high-impact visuals, it’s no wonder why interstitial advertising is proving

positive contribution tech

Technology’s Positive Contributions to Society

Technology has and continues to improve our lives. From the business world to the world of medicine, and our day-to-day lives, you can’t go a day without interacting with at least one form of technology. While some fear technology may be going too far, there are many ways in which

How to Choose From The Best Big Data Platforms in 2023

How to Choose From The Best Big Data Platforms in 2023

As big data continues to become increasingly popular in the business world, companies are always looking for better ways to process and analyze complex data. The process critically depends on the platform that manages and analyzes the data. In this article, we will provide a guide to help you choose

Why transparent code is a good idea

Why Transparent Code is a Good Idea

Code is used to make up the apps and software we use every day. From our favorite social media platforms to our online banking services, code is the framework used to build these tools that help make our lives easier. Code is complex. Software today requires large teams of programmers

The Role of WordPress Hosting in Website Speed and Performance

The Role of WordPress Hosting in Website Performance

The term “WordPress hosting” refers to a specific type of web hosting service that offers hardware and software configurations tailored to the needs of WP sites. It’s important to remember that a WP hosting package is not required to host WordPress webpages. WP web pages are also compatible with standard