IEnumerable选择 [英] IEnumerable Select

查看:73
本文介绍了IEnumerable选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么C#的下一行与下面的foeach块的行为不同吗?

Can someone explain why the following line of C# doesn't behave the same as the following foeach block?

string [] strs = {"asdf", "asd2", "asdf2"};
strs.Select(str => doSomething(str));


foreach(string str in strs){
  doSomething(str);
}

我在doSomething()中放置了一个断点,它在Select中不触发,但它与foreach一样.

I put a breakpoint inside of doSomething() and it doesn't fire in the Select but it does with the foreach.

TIA

推荐答案

在使用ToList()ToArray()等将其转换为Enumarable之前,不会处理Linq查询.

The Linq query won't be processed until you convert it to an Enumarable using ToList(), ToArray(), etc.

顺便说一句,与您的foreach语句等效的是这样的:

And by the way the equivalent to your foreach statement is something like this:

strs.ForEach(doSomething);

strs.ToList().ForEach(doSomething);

Array.ForEach(strs, doSomething);

这篇关于IEnumerable选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆