Use property instead of Linq Enumerable method
Use property instead of Linq Enumerable method
Microsoft docsDescription
This rule flags the System.Linq.Enumerable LINQ method calls on collections of types that have equivalent but more efficient properties to fetch the same data.
This rule analyzes collection types that implement System.Collections.Generic.IReadOnlyList1 but not System.Collections.Generic.IList1.
This rule flags calls to the following methods on these collection types:
- System.Linq.Enumerable.Count
- System.Linq.Enumerable.First
- System.Linq.Enumerable.FirstOrDefault
- System.Linq.Enumerable.Last
- System.Linq.Enumerable.LastOrDefault
The analyzed collection types and methods may be extended in the future to cover more cases.
Cause
The System.Linq.Enumerable LINQ method was used on a type that supports an equivalent, more efficient property.
How to fix violations
To fix a violation, replace the System.Linq.Enumerable method call with property access. For example, the following two code snippets show a violation of the rule and how to fix it: A code fix is available for this rule in Visual Studio. To use it, position the cursor on the violation and press <kbd>Ctrl</kbd>+<kbd>.</kbd> (period). Choose Use indexer from the list of options that's presented. !Code fix for CA1826 - Use indexer
Example
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());
}
}When to suppress
It's safe to suppress a violation of this rule if you're not concerned about the performance impact from specific System.Linq.Enumerable method calls.