SoFunction
Updated on 2025-03-06

C# Linq delay query execution instance code

C# Linq Delay Query

When defining a linq query expression, the query will not be executed, and the query will run when iterating over the data items. It uses the yield return statement to return elements with the predicate true.

var names = new List<string> { "Nino", "Alberto", "Juan", "Mike", "Phil" };
var namesWithJ = from n in names
                 where ("J")
                 orderby n
                 select n;
("First iteration");
foreach (string name in namesWithJ) 
{
    (name);
}
();

("John");
("Jim");
("Jack");
("Denny");

("Second iteration");
foreach (string name in namesWithJ)
{
    (name);
}

The result of the operation is

First iteration
Juan

Second iteration
Jack
Jim
John
Juan

From the execution results, it can be seen that when defining namesWithJ, it will not be executed, but will be executed when each foreach statement is executed, so the subsequent "John", "Jim", "Jack" and "Denny" will also participate in the second iteration.

ToArray(), ToList() and other methods can change this operation and modify the definition statement of namesWithJ to

var namesWithJ = (from n in names
                  where ("J")
                  orderby n
                  select n).ToList();

The result of the operation is

First iteration
Juan

Second iteration
Juan

In daily work, we often use (x=> == XXX).FirstOrDefault() and (x=> == XXX). In fact, the performance of these two writing methods is equivalent. If you really want to distinguish between performance, please see below

Comparison of C# performance

Today we will compare the better performance of the collection search method and test the code

public class Entity
{
    public int Id { get; set; }
    public int No { get; set; }
    public string Col1 { get; set; }
    public string Col2 { get; set; }
    public string Col3 { get; set; }
    public string Col4 { get; set; }
    public string Col5 { get; set; }
    public string Col6 { get; set; }
    public string Col7 { get; set; }
    public string Col8 { get; set; }
    public string Col9 { get; set; }
    public string Col10 { get; set; }
}
static void TestFindVelocity(int totalDataCount, int executeCount)
{
    #region Construct data    List&lt;Entity&gt; datas = new List&lt;Entity&gt;();
    for (int i = 0; i &lt; totalDataCount; i++)
    {
        var item = new Entity
        {
            No = i + 1,
            Col1 = ().ToString("N"),
            Col2 = ().ToString("N"),
            Col3 = ().ToString("N"),
            Col4 = ().ToString("N"),
            Col5 = ().ToString("N"),
            Col6 = ().ToString("N"),
            Col7 = ().ToString("N"),
            Col8 = ().ToString("N"),
            Col9 = ().ToString("N"),
            Col10 = ().ToString("N"),
        };
        (item);
    }
    #endregion
    var dicDatas = (x =&gt; );
    var hashSetDatas = &lt;Tuple&lt;int, int&gt;&gt;(x =&gt; new Tuple&lt;int, int&gt;(,  + 1000)).ToHashSet();
    Stopwatch sw = new Stopwatch();
    Random random = new Random();
    Entity searchResult = null;
    bool searchResultBool = false;
    // Each time you query the index    List&lt;int&gt; indexs = (1, executeCount).Select(x =&gt; (1, totalDataCount)).ToList();

    ();
    for (int i = 0; i &lt; executeCount; i++)
    {
        searchResult = (x =&gt;  == indexs[i]);
    }
    ();
    ($"list FirstOrDefault time consuming:{}");

    ();
    for (int i = 0; i &lt; executeCount; i++)
    {
        searchResult = (x =&gt;  == indexs[i]).First();
    }
    ();
    ($"list Where+First time consuming:{}");

    ();
    for (int i = 0; i &lt; executeCount; i++)
    {
        searchResultBool = (x =&gt;  == indexs[i]);
    }
    ();
    ($"list Exist time consuming:{}");

    ();
    for (int i = 0; i &lt; executeCount; i++)
    {
        searchResult = (x =&gt;  == indexs[i]);
    }
    ();
    ($"list Find time consuming:{}");

    ();
    for (int i = 0; i &lt; executeCount; i++)
    {
        (indexs[i], out searchResult);
    }
    ();
    ($"dictionary TryGetValue time consuming:{}");

    ();
    for (int i = 0; i &lt; executeCount; i++)
    {
        searchResultBool = (new Tuple&lt;int, int&gt;(indexs[i], indexs[i] + 1000));
    }
    ();
    ($"Hashset contains time consuming:{}");
}

result

(Number of collections, number of tests) +First

(100, 5000000)

4544 3521 1992 1872 66 924

(1000, 5000000)

41751 29417 20631 19490 70 869

(10000, 5000000)

466918 397425 276409 281647 85 946

(50000, 5000)

6292 4602 4252 3559 0 2

(500000, 5000)

56988 55568 48423 48395 1 5

The errors should be avoided(x=> == XXX).ToList()[0]

Summarize

This is the end of this article about the execution of C# Linq delay query. For more related C# Linq delay query content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!