Using LINQ in a foreach loop declaration

Is it wrong practice to declare LINQ directly in a foreach loop declaration? In terms of performance or subtle differences in behavior.

For instance:

foreach (string name in persons.Select(x => x.name)) { //Do something with name } 
+4
source share
2 answers

Nope. There is nothing wrong. As long as the Linq expression is short and easy to read, I would say the most important thing. Your example is a really good example of when such queries should be used in this way.

If it is much longer than this or if you use the query syntax, I recommend splitting it into two lines as follows:

 var names = persons.Select(x => x.name).Blah().Blah().Blah(); foreach (string name in names) { //Do something with name } 

or

 var names = from x in persons select x.name; foreach (string name in names) { //Do something with name } 
+4
source

Bad practice? Not at all.

Performance may be affected, though, depending on the situation. For example, this:

 persons.Select(x => x.name).Select(x => x.name + " more"); 

May work better than this:

 foreach(string name in persons.Select(x => x.name)) { someList.Add(name + " more"); } 

... if you use something like the Entity Framework, where name + " more" will happen on the database side compared to the local memory in the first example.

The best practice, in my opinion, is to go with what is most readable, and then if you run into performance problems, you can set up a profile. Sometimes it is clearer to use LINQ to create IEnumerable, but foreach to create more complex things. If the LINQ part is too long, I would go with:

 var somethings = something.Where(x => x == 1).Where(...).GroupBy(...etc); foreach(var something in somethings) { // Do something } 
+3
source

Source: https://habr.com/ru/post/1484109/


All Articles