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.
Replace explicit loops and conditional blocks with equivalent LINQ expressions.
Use the System.Linq.Async package to enable LINQ operations on IAsyncEnumerable prior to .NET 10.
List<string> Method(IEnumerable<string> collection, Predicate<string> condition)
{
var result = new List<string>();
foreach (var element in collection) // Noncompliant
{
if (condition(element))
{
result.Add(element);
}
}
return result;
}
List<string> Method(IEnumerable<MyDto> collection)
{
var result = new List<string>();
foreach (var element in collection) // Noncompliant
{
var someValue = element.Property;
if (someValue != null)
{
result.Add(someValue);
}
}
return result;
}
async Task<List<string>> Method(IAsyncEnumerable<string> collection)
{
var result = new List<string>();
await foreach (var element in collection) // Noncompliant
{
if (element != null)
{
result.Add(element);
}
}
return result;
}
List<string> Method(IEnumerable<string> collection, Predicate<string> condition) => collection.Where(x => condition(x)).ToList();
List<string> Method(IEnumerable<MyDto> collection) => collection.Select(x => x.Property).Where(y => y != null).ToList();
List<string> Method(IAsyncEnumerable<string> collection) => collection.Where(x => x != null).ToList();