Is it bad practice to declare LINQ directly in a foreach loop declaration? In terms of performance or subtle behavioral differences.
For example:
foreach (string name in persons.Select(x => x.name))
{
//Do something with name
}
Convert a foreach loop to LINQ refactoringPlace your cursor in the foreach keyword. Press Ctrl+. to trigger the Quick Actions and Refactorings menu. Select Convert to LINQ or Convert to Linq (call form).
It is slightly slower LINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code. And if you'd like to measure the performance difference, you can use a tool like BenchmarkDotNet to do so.
The linq parallel foreach will partition your collection and work on it at the same time, which you also need to take into account making sure your this. Update can work with multiple users without messing up .
The IEnumerator interface provides iteration over a collection-type object in a class. The IEnumerable interface permits enumeration by using a foreach loop.
Nope. Nothing wrong with that. As long as the Linq expression is short and easily readable, I'd say that's the most important thing. Your example is a really good example of when such queries should be use that way.
If it get's much longer than that or if you use query syntax, however, I recommend splitting it into two lines like this:
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
}
Bad practice? Not at all.
Performance could be impacted though, depending on the situation. For example, this:
persons.Select(x => x.name).Select(x => x.name + " more");
Could perform better than this:
foreach(string name in persons.Select(x => x.name))
{
someList.Add(name + " more");
}
...if you're using something like Entity Framework where the name + " more"
would happen on the database side vs local memory in the first example.
The best practice in my opinion is to go with whatever is most readable, then if you experience performance issues you can profile/tweak. Sometimes its clearer to use LINQ to build the IEnumerable, but the foreach to do some trickier stuff. If the LINQ part gets too long though, I would go with:
var somethings = something.Where(x => x == 1).Where(...).GroupBy(...etc);
foreach(var something in somethings)
{
// Do something
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With