CA1826: Use property instead of Linq Enumerable method
| Value | |
|---|---|
| Rule ID | CA1826 |
| Category | Performance |
| Fix is breaking or non-breaking | Non-breaking |
Cause
The Enumerable LINQ method was used on a type that supports an equivalent, more efficient property.
Rule description
This rule flags the Enumerable LINQ method calls on collections of types that have equivalent, but more efficient properties to fetch the same data.
This rule analyzes the following collection types:
- A type that implements IReadOnlyList<T>, but not IList<T>
This rule flags calls to following methods on these collection types:
- System.Linq.Enumerable.Count method
- System.Linq.Enumerable.First method
- System.Linq.Enumerable.FirstOrDefault method
- System.Linq.Enumerable.Last method
- System.Linq.Enumerable.LastOrDefault method
The analyzed collection types and/or methods may be extended in future to cover more cases.
How to fix violations
To fix a violation, replace the Enumerable method calls with property access. For example, the following two code snippets show a violation of the rule and how to fix it:
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
public void M(IReadOnlyList<string> list)
{
Console.Write(list.First());
Console.Write(list.Last());
Console.Write(list.Count());
}
}
using System;
using System.Collections.Generic;
class C
{
public void M(IReadOnlyList<string> list)
{
Console.Write(list[0]);
Console.Write(list[list.Count - 1]);
Console.Write(list.Count);
}
}
Tip
A code fix is available for this rule in Visual Studio. To use it, position the cursor on the violation and press Ctrl+. (period). Choose Use indexer from the list of options that's presented.

When to suppress warnings
It's safe to suppress a violation of this rule if you're not concerned about the performance impact from specific Enumerable method calls.
Suppress a warning
If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable CA1826
// The code that's violating the rule is on this line.
#pragma warning restore CA1826
To disable the rule for a file, folder, or project, set its severity to none in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1826.severity = none
To disable this entire category of rules, set the severity for the category to none in the configuration file.
[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Performance.severity = none
For more information, see How to suppress code analysis warnings.
Related rules
- CA1827: Do not use Count/LongCount when Any can be used
- CA1828: Do not use CountAsync/LongCountAsync when AnyAsync can be used
- CA1829: Use Length/Count property instead of Enumerable.Count method
See also
Povratne informacije
Pošalјite i prikažite povratne informacije za