简体   繁体   中英

Does Select followed by Where result in two iterations over the IEnumerable?

Let say I have

IEnumerable<int> list = new int[] { 1, 2, 3 };
List<int> filtered = list.Select(item => item * 10).Where(item => item < 20).ToList();

The question is are there two iterations or just one.

In other words, is that equivalent in performance to:

IEnumerable<int> list = new int[] { 1, 2, 3 };
List<int> filtered = new List<int>();
foreach(int item in list) {
    int newItem = item * 10;
    if(newItem < 20)
        filtered.Add(newItem);
}

There is a single iteration over the collection performed when you call the .ToArray method so both should be equivalent. .Select is a projection and .Where is a filter, both expressed as expression trees on the original dataset.

Could be easily proven:

public class Foo: IEnumerable<int>
{
    public IEnumerator<int> GetEnumerator()
    {
        yield return 1;
        Console.WriteLine("we are at element 1");
        yield return 2;
        Console.WriteLine("we are at element 2");
        yield return 3;
        Console.WriteLine("we are at element 3");
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

class Program
{
    static void Main()
    {
        var filtered = new Foo()
            .Select(item => item * 10)
            .Where(item => item < 20)
            .ToList();
    }
}

when run prints the following:

we are at element 1
we are at element 2
we are at element 3

In Linq to Objects WHERE and SELECT do not iterate over the enumerable. The calling code enumerates it when it does a foreach on the query or ToList or ToArray(), etc.

In Linq to SQL there is no iteration what so ever. When you do ToList or ToArray() the query is executed by database. Depending on the type of query db could look up indexes or do a table scan.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM