A sequence is copied into a list or array only to count it or to test it for elements

tx0/csharp:materialized-to-countrecommendedwarningperformance/allocationdepth fastperformance

What it finds

query.ToList().Count builds a list of every element and throws it away after reading one number; query.Count() counts without the copy, and query.Any() stops at the first element. The rule reports Count, Length, Count() and Any() right after ToList() or ToArray().

From the rule's source, materialized_to_count.rs.

Example from the rule's tests
using System.Collections.Generic;using System.Linq; class Orders{    int Open(IEnumerable<int> orders) => orders.Where(o => o > 0).ToList().Count;tx0 reports: the sequence is copied by ToList only to be counted     int Direct(IEnumerable<int> orders) => orders.Count(o => o > 0);}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/csharp:materialized-to-count" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/csharp:materialized-to-count] reason="..."

tx0 explain tx0/csharp:materialized-to-count shows the same in the terminal. Found a false positive? Report it.