Using explicit loops for filtering, selecting, or aggregating elements can make code more verbose and harder to read. LINQ expressions provide a
more concise and expressive way to perform these operations, improving code clarity and maintainability.
Performance Considerations
If the affected code is part of a performance-critical hot path and that the fix would negatively impact performance, you can self-declare the
PerformanceSensitiveAttribute
in your codebase, or use the one provided by Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers:
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
public sealed class PerformanceSensitiveAttribute() : Attribute;
[PerformanceSensitiveAttribute]
List<string> Method(IEnumerable<string> collection, Predicate<string> condition)
{
var result = new List<string>();
foreach (var element in collection) // Without the attribute, this would raise an issue
{
if (condition(element))
{
result.Add(element);
}
}
return result;
}
The rule will respect the AllowGenericEnumeration
property:
[PerformanceSensitive("Enumeration", AllowGenericEnumeration = true)]
List<string> Method(IEnumerable<string> collection, Predicate<string> condition) { }
In this case, the rule will not be disabled even if the method is marked with the PerformanceSensitiveAttribute
attribute.