代码检查:替换为 OfType<T>().Last()(替换为 OfType<T>().Last(..))
此检查报告了一个使用 as 强制转换元素、过滤 null ,然后查找满足额外条件的最后一个元素的 LINQ 查询。 相同的查询使用 OfType<T>().Last(...) 更易阅读。
示例
var last = items.Select(x => x as Person).Last(y => y != null && y.IsActive);
var last = items.OfType<Person>().Last(y => y.IsActive);
快速修复
将 Select(... as T).Last(y => y != null && ...) 模式替换为 OfType<T>().Last(...)。
2026年 5月 8日