Biên tập

Chia sẻ qua


Simplify LINQ type check and cast (IDE0121)

Property Value
Rule ID IDE0121
Title Simplify LINQ type check and cast
Category Style
Subcategory Unnecessary code rules (expression-level preferences)
Applicable languages C# and Visual Basic

Overview

This rule flags LINQ expressions where the type of elements of a sequence are checked (by calling Where<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)) and then cast to that type (by calling either Cast<TResult>(IEnumerable) or Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>)). The code fixer converts these expressions to call OfType<TResult>(IEnumerable) instead.

Options

This rule has no associated code-style options.

Example

// Code with violations.
IEnumerable<int> y = objects.Where(a => a is int).Cast<int>();
IEnumerable<int> z = objects.Where(a => a is int).Select(a => (int)a);

// Fixed code.
IEnumerable<int> y = objects.OfType<int>();
IEnumerable<int> z = objects.OfType<int>();

Suppress a warning

If you want to suppress only a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable IDE0121
// The code that's violating the rule is on this line.
#pragma warning restore IDE0121

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.IDE0121.severity = none

To disable all of the code-style rules, set the severity for the category Style to none in the configuration file.

[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Style.severity = none

For more information, see How to suppress code analysis warnings.

See also