Mike_G
Mike_G

Reputation: 16502

When is this LINQ query executed?

public class TestClass
{
    public TestClass(int id, string name)
    {
        Name = name;
        Id = id;
    }
    public string Name
    { get; private set; }

    public int Id
    { get; private set; }

    public string Tag
    { get; set; }

    public DateTime Time
    { get; set; }
}

 private static void Main(string[] args)
    {
        List<TestClass> list = new List<TestClass>();

        for (int i = 0; i < 5; i++ )
        {
            TestClass t = new TestClass(i, Guid.NewGuid().ToString());
            t.Tag = i%2 == 0?"Hello":"World";
            list.Add(t);
        }

        var query = list
            .GroupBy(l=>l.Tag);

        Func<IEnumerable<IGrouping<string, TestClass>>, int[]> func = GetIds<string,TestClass>;

        func.BeginInvoke(query, null, null);

        Console.Read();
    }

    private static int[] GetIds<T, U>(IEnumerable<IGrouping<T, U>> query)
    {
        List<int> ints = new List<int>();

        foreach(var y in query)
            ints.Add(y.Count());

        return ints.ToArray();
    }
}

I know LINQ doesnt execute until the collection is iterated, but i just want to make sure that I can assume that it still holds true even if the query is passed to another method async.

Upvotes: 4

Views: 6945

Answers (4)

Sanu Uthaiah Bollera
Sanu Uthaiah Bollera

Reputation: 937

The following illustration shows the complete query operation. In LINQ the execution of the query is distinct from the query itself,See below.

enter image description here

Source :: MSDN

Upvotes: 2

bytebender
bytebender

Reputation: 7491

It is executed when you call ints.ToArray(); shouldn't matter that it in a different thread...

EDIT: I stand corrected, It would execute in the ForEach...

Upvotes: 1

MattH
MattH

Reputation: 4227

As I understand it, it will still hold true asynchronously, however the execution may not be threadsafe. LINQ to SQL's DataContexts for example aren't threadsafe, and therefore LINQ to SQL queries should not be executed in another thread in that manner.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500495

Yes, query execution is still deferred. The query is just a reference to an implementation of IEnumerable<T> which in turn knows about another IEnumerable<T> (along with appropriate delegates for filtering, grouping etc).

Note that if you iterate over it a second time (in whatever thread) that will execute the query again. The query reference knows how to get the data - it doesn't know the data itself.

Upvotes: 18

Related Questions