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 that LINQ is not executed until the collection is iterated, but I just want to make sure that I can assume that it is still saved even if the request is passed to another async method.

+4
source share
4 answers

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

Please note that if you repeat it a second time (in any thread) that will execute the request again. The request link knows how to get the data - it does not know the data itself.

+16
source

As I understand it, it will continue to be executed asynchronously, however, execution may be unsafe. For example, LINQ to SQL DataContexts are not thread safe, so LINQ to SQL queries should not be executed on another thread this way.

+3
source

It is executed when you call ints.ToArray(); , it doesnโ€™t matter that he is in another thread ...

EDIT: I stand fixed, it will run in ForEach ...

+1
source

The following figure shows the complete query operation. In LINQ, query execution is different from the query itself, see below.

enter image description here

Source: MSDN

+1
source

All Articles