In Visual Studio Re-Sharper keeps recommending I convert a for loop to a linq expression but what is the reason for this?
Which is faster?
Here are some example loops where resharper suggests a linq conversion:
foreach (XmlNode legendEntryNode in _legendEntryNodes)
{
var xmlElement = legendEntryNode["FeatureType"];
if (xmlElement == null || !xmlElement.InnerText.Equals(featuretype)) continue;
var xmlNodeList = legendEntryNode.SelectNodes("Themes/Theme");
if (xmlNodeList != null)
foreach (XmlNode themeNode in xmlNodeList)
{
var element = themeNode["Value"];
if (element == null || !element.InnerText.Equals(v)) continue;
var xmlElement1 = themeNode["Icon"];
if (xmlElement1 != null)
{
string iconname = "<ms:ICON>" + xmlElement1.InnerText + "</ms:ICON>";
var element1 = themeNode["Highlight"];
if (element1 != null)
{
string highlightname = "<ms:HIGHLIGHT>" + element1.InnerText + "</ms:HIGHLIGHT>";
gml = gml.Insert(c, iconname + highlightname);
c += (iconname.Length + highlightname.Length);
}
}
break;
}
}
And this simpler example:
for (int i = 0; i < getPointsRequest.Attribs.Length; i++)
{
string attribName = getPointsRequest.Attribs[i].AttributeName;
if (!String.IsNullOrEmpty(attribName))
{
sqlQuery += "<ms:" + attribName + ">||\"" + attribName + "\"||</ms:" + attribName + ">";
}
}
Speed is very often irrelevant in large portions of your code – you should write code the simplest way, and then measure it to make sure it’s fast enough.
If your for loop is really just querying, then LINQ is absolutely a great way to end up with more readable code. It’s not universally applicable, but it’s something you should at least bear in mind frequently.
Quite often a for loop can be converted into a query to be evaluated lazily, and then a foreach loop which performs some action on each value returned by the query. That can help separate the two aspects, letting you focus on one at a time when reading the code. It’s important to keep LINQ queries as queries though, rather than using side-effects within them – it’s designed to have a functional approach, which really doesn’t mix pleasantly with side-effects.
If you have some concrete examples, we could give more opinions about which loops would make sense to convert to use LINQ, and which wouldn’t.