Skip to main content

ToArrayOrToListFollowedByLinqMethod

Diagnostic Rule Overview

FieldValue
IDSHIMMER1011
Analyzer titleUnnecessary materialization to array/list in LINQ chain
Analyzer messageRemove unnecessary materialization to an array or a list
Code fix titleRemove unnecessary materialization
Default severityWarning
Minimum framework/language versionN/A
CategoryShimmeringUsage
Link to codeToArrayOrToListFollowedByLinqMethodAnalyzer.cs
Code fix exists?Yes

Detailed Explanation

Materializing an IEnumerable<T> before further processing adds unnecessary overhead. LINQ operations should be performed before materialization.

Note that this diagnostic is not triggered if the preceding enumerable implements IQueryable<T>, as using materializing may be required when, for example, talking to the database.

Examples

Flagged code:

using System.Collections.Generic;
using System.Linq;

namespace Tests;
class Test
{
void Do()
{
int[] numbers = [];
var greaterThanThree = numbers.ToArray().Where(x => x > 3);
}
}

Fixed code:

using System.Collections.Generic;
using System.Linq;

namespace Tests;
class Test
{
void Do()
{
int[] numbers = [];
var greaterThanThree = numbers.Where(x => x > 3);
}
}

Justification of the Severity

While this is not a bug, this will slow down your code and increase memory usage with no benefits. As a reminder, the diagnostic doesn't flag if the preceding enumerable implements IQueryable<T>, which is likely the main case where you'd actually want to allocate a list.

Inspiration

This was inspired by @Treit's blog post https://mtreit.com/programming,/.net/2024/07/30/ToList.html. The same material was also covered in this YouTube video.