开发者

Convert linq method syntax to query syntax

Not that it would be better, but I'm trying to get my head around turning the following method syntax to query syntax to see the difference.

long diskSpace = Directory.EnumerateDirectories(@"c:\")
                    .SelectMany(Di开发者_StackOverflowrectory.EnumerateFiles)
                    .Sum(fileSize => new FileInfo(fileSize).Length);


That query is mostly equivalent to:

long diskSpace = (from directory in Directory.EnumerateDirectories(@"c:\")
                  from file in Directory.EnumerateFiles(directory)
                  select file)
                 .Sum(file => new FileInfo(file).Length);

(I've renamed fileSize to file to more accurately represent the meaning, btw.)

There's one actual difference in this case - we're creating a new delegate which calls Directory.EnumerateFiles rather than directly creating a delegate from the Directory.EnumerateFiles method group. In other words, it's one extra level of redirection - but this won't have any effect on the results and I'd be amazed if it had any significant performance impact.


There's no difference.

The compiler translates query syntax aka LINQ, into these methods calls. Query syntax is just syntactic suguar. It's not magic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜