简体   繁体   中英

Translating query comprehension to Enumerable extension methods in LINQ

How do I translate the following query to functional calls? I know the compiler does this behind the scenes but don't know how I would view the result

        var query = from item in Enumerable.Range(0, 10)
                    from item2 in Enumerable.Range(item, 10)
                    from item3 in Enumerable.Range(item2, 10)
                    select new { item, item2, item3 };

In this case, it uses SelectMany , and a concept called transparent identifiers which preserve the existing range variables. So your query would translate to:

var query = Enumerable.Range(0, 10)
                      .SelectMany(item => Enumerable.Range(item, 10),
                                  (item, item2) => new { item, item2 })
                      .SelectMany(z => Enumerable.Range(z.item2, 10),
                                  (z, item3) => new { z.item, z.item2, item3 });

(In this case z is the transparent identifier. If there'd been a where clause or anything other than a select after the last from clause, another transparent identifier would have been introduced.)

The translations are all described in the C# language specification, section 7.16.

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