Latency query and latency Query

Source: Internet
Author: User

Latency query and latency Query

LINQ defines a series of standard query operators. We can use these operators to query the data source using the query syntax or method syntax. After defining the query statement, LINQ does not immediately query the data source, the data source is queried only when the returned results are traversed through foreach. This technique is called the latency query of LINQ. For example:

// Latency query int [] numbers = new int [] {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}; int I = 0; var q = numbers. where (x => {I ++; return x> 2 ;}); foreach (var v in q) {Console. writeLine ("v = {0}, I = {1}", v, I );}

The code output is as follows:

It can be seen that the program performs the query only when executing the foreach loop. At this time, the program is slightly modified and the query result is converted to List:

// Latency query int [] numbers = new int [] {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}; int I = 0; var q = numbers. where (x => {I ++; return x> 2 ;}). toList (); foreach (var v in q) {Console. writeLine ("v = {0}, I = {1}", v, I );}

Execution result

When the program executes the ToList operation, it has already performed the query. Therefore, all the I values returned are 10. The latency query of LINQ is so, let's look at the source code of the extension method Where, which is in the Enumerable static class (http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,577032c8811e20d3) under the System. Linq namespace ):

public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {            if (source == null) throw Error.ArgumentNull("source");            if (predicate == null) throw Error.ArgumentNull("predicate");            if (source is Iterator<TSource>) return ((Iterator<TSource>)source).Where(predicate);            if (source is TSource[]) return new WhereArrayIterator<TSource>((TSource[])source, predicate);            if (source is List<TSource>) return new WhereListIterator<TSource>((List<TSource>)source, predicate);            return new WhereEnumerableIterator<TSource>(source, predicate);        }

That is to say, var q = numbers is defined. where (x => {I ++; return x> 2 ;}); the program only returns a WhereArrayIterator <TSource> object, this object has a reference to the source data and lambda expressions. The source code of this class is as follows:

class WhereArrayIterator<TSource> : Iterator<TSource>{    TSource[] source;    Func<TSource, bool> predicate;    int index;    public WhereArrayIterator(TSource[] source, Func<TSource, bool> predicate) {        this.source = source;        this.predicate = predicate;    }    public override Iterator<TSource> Clone() {        return new WhereArrayIterator<TSource>(source, predicate);    }    public override bool MoveNext() {        if (state == 1) {            while (index < source.Length) {                TSource item = source[index];                index++;                if (predicate(item)) {                    current = item;                    return true;                }            }            Dispose();        }        return false;    }    public override IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) {        return new WhereSelectArrayIterator<TSource, TResult>(source, predicate, selector);    }    public override IEnumerable<TSource> Where(Func<TSource, bool> predicate) {        return new WhereArrayIterator<TSource>(source, CombinePredicates(this.predicate, predicate));    }}

We can see the if (predicate (item) Statement in the MoveNext () method. The program judges each value of the source data here, therefore, when the returned WhereArrayIterator <TSource> object is recycled, the compiler implicitly calls its MoveNext method to execute the query.

Let's look at the ToList extension method under the Enumerable class:

public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source) {            if (source == null) throw Error.ArgumentNull("source");            return new List<TSource>(source);        }

The ToList method returns a new List <TSource> object. Let's look at the List <TSource> constructor.

public List(IEnumerable<T> collection) {    if (collection==null)        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);    Contract.EndContractBlock();    ICollection<T> c = collection as ICollection<T>;    if( c != null) {        int count = c.Count;        if (count == 0)        {            _items = _emptyArray;        }        else {            _items = new T[count];            c.CopyTo(_items, 0);            _size = count;        }    }        else {                        _size = 0;        _items = _emptyArray;        // This enumerable could be empty.  Let Add allocate a new array, if needed.        // Note it will also go to _defaultCapacity first, not 1, then 2, etc.                using(IEnumerator<T> en = collection.GetEnumerator()) {            while(en.MoveNext()) {                Add(en.Current);                                                }        }    }}

The constructor converts metadata to ICollection. Because our metadata type cannot be converted to ICollection, null is returned. Then, the code of the else segment is executed and en is executed here. moveNext () to query the data source.

  

 

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.