Foreach c# là gì

I have an Enumerable và am looking for a method that allows me to execute an kích hoạt for each element, kind of lượt thích Select but then for side-effects. Something like:

string<> Names = ...;Names.each(s => Console.Writeline(s));or

Names.each(s => GenHTMLOutput(s)); // (where GenHTMLOutput cannot for some reason receive the enumerable itself as a parameter)I did try Select(s=> Console.WriteLine(s); return s; ), but it wasn"t printing anything.

Bạn đang xem: Foreach c# là gì




Disclaimer: This post no longer resembles my original answer, but rather incorporates the some seven years experience I"ve gained since. I made the edit because this is a highly-viewed question & none of the existing answers really covered all the angles. If you want lớn see my original answer, it"s available in the revision history for this post.

The first thing lớn understand here is C# linq operations lượt thích Select(), All(), Where(), etc, have their roots in functional programming. The idea was to lớn bring some of the more useful and approachable parts of functional programming lớn the .Net world. This is important, because a key tenet of functional programming is for operations khổng lồ be free of side effects. It"s hard lớn understate this. However, in the case of ForEach()/each(), side effects are the entire purpose of the operation. Adding each() or ForEach() is not just outside the functional programming scope of the other linq operators, but in direct opposition khổng lồ them.

But I understand this feels unsatisfying. It may help explain why ForEach() was omitted from the framework, but fails lớn address the real issue at hand. You have a real problem you need to lớn solve. Why should all this ivory tower philosophy get in the way of something that might be genuinely useful?

Eric Lippert, who was on the C# kiến thiết team at the time, can help us out here. He recommends using a traditional foreach loop:

adds zero new representational power to lớn the language. Doing this lets you rewrite this perfectly clear code:

foreach(Foo foo in foos) statement involving foo;

into this code:

foos.ForEach(foo=> statement involving foo; );

His point is, when you look closely at your syntax options, you don"t gain anything new from a ForEach() extension versus a traditional foreach loop. I partially disagree. Imagine you have this:

foreach(var thành công in Some.Long(and => possibly) .Complicated(set => ofLINQ) .Expression(to => evaluate)) // now vày something This code obfuscates meaning, because it separates the foreach từ khoá from the operations in the loop. It also lists the loop command prior khổng lồ the operations that define the sequence on which the loop operates. It feels much more natural to want to lớn have those operations come first, and then have the the loop command at the end of the query definition. Also, the code is just ugly. It seems like it would be much nicer to be able to write this:

Some.Long(and => possibly) .Complicated(set => ofLINQ) .Expression(to => evaluate) .ForEach(item => // now bởi vì something);However, even here, I eventually came around lớn Eric"s point of view. I realized code lượt thích you see above is calling out for an additional variable. If you have a complicated set of LINQ expressions like that, you can địa chỉ cửa hàng valuable information khổng lồ your code by first assigning the result of the LINQ expression to a new variable:

var queryForSomeThing = Some.Long(and => possibly) .Complicated(set => ofLINQ) .Expressions(to => evaluate);foreach(var thành công in queryForSomeThing) // now vày somethingThis code feels more natural. It puts the foreach từ khóa back next to lớn the rest of the loop, & after the query definition. Most of all, the variable name can địa chỉ cửa hàng new information that will be helpful khổng lồ future programmers trying to lớn understand the purpose of the LINQ query. Again, we see the desired ForEach() operator really added no new expressive power to the language.

Xem thêm: Khối Lượng Riêng, Trọng Lượng Riêng Là Gì ? Công Thức Tính Khối Lượng Riêng

However, we are still missing two features of a hypothetical ForEach() extension method:

It"s not composable. I can"t add a further .Where() or GroupBy() or OrderBy() after a foreach loop inline with the rest of the code, without creating a new statement.It"s not lazy. These operations happen immediately. It doesn"t allow me to, say, have a size where a user chooses an operation as one field in a larger screen that is not acted on until the user presses a command button. This form might allow the user lớn change their mind before executing the command. This is perfectly normal (easy even) with a LINQ query, but not as simple with a foreach.

(FWIW, most naive .ForEach() implementations also have these issues. But it"s possible khổng lồ craft one without them.)

You could, of course, make your own ForEach() extension method. Several other answers have implementations of this method already; it"s not all that complicated. However, I feel lượt thích it"s unnecessary. There"s already an existing method that fits what we want to do from both semantic and operational standpoints. Both of the missing features above can be addressed by use of the existing Select() operation.

Xem thêm: Nghĩa Của Từ Advisor Là Gì ? Định Nghĩa, Ví Dụ, Giải Thích Định Nghĩa, Ví Dụ, Giải Thích

Select() fits the kind of transformation or projection described by both of the examples above. Keep in mind, though, that I would still avoid creating side effects. The hotline to Select() should return either new objects or projections from the originals. This can sometimes be aided through the use of an anonymous type or dynamic object (if and only if necessary). If you need the results to lớn persist in, say, an original danh mục variable, you can always gọi .ToList() và assign it back khổng lồ your original variable. I"ll add here that I prefer working with IEnumerable variables as much as possible over more concrete types.

myList = myList.Select(item => new SomeType(item.value1, item.value2 *4)).ToList();In summary:

Just stick with foreach most of the time.When foreach really won"t vì (which probably isn"t as often as you think), use Select()When you need to use Select(), you can still generally avoid (program-visible) side effects, possibly by projecting to an anonymous type.Avoid the crutch of calling ToList(). You don"t need it as much as you might think, and it can have significant negative consequence for performance và memory use.