Fix the LINQ optimization rules on predicates, casts, ordering and collection interfaces - #1585
Merged
Merged
Conversation
…llection interfaces
meziantou
marked this pull request as ready for review
September 23, 2026 04:49
This was referenced Sep 23, 2026
Bump Meziantou.Analyzer from 3.0.139 to 3.0.283
Analogy-LogViewer/Analogy.LogViewer.NLog.Targets#582
Closed
Closed
Bump Meziantou.Analyzer from 3.0.139 to 3.0.283
Analogy-LogViewer/Analogy.AspNetCore.LogProvider#563
Closed
Closed
Closed
Closed
Closed
Closed
Closed
Closed
This was referenced Oct 1, 2026
Open
Open
Open
Bump Meziantou.Analyzer from 3.0.139 to 3.0.291
Analogy-LogViewer/Analogy.LogViewer.NLog.Targets#586
Open
Bump Meziantou.Analyzer from 3.0.139 to 3.0.291
Analogy-LogViewer/Analogy.AspNetCore.LogProvider#565
Open
Open
Open
Open
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Several bugs in
OptimizeLinqUsageAnalyzer/OptimizeLinqUsageFixer, most of them code fixes that produce code that doesn't compile or that behaves differently at runtime.MA0029 (Combine LINQ methods)
items.Where(f).Any(g)(withFunc<int, bool> f, g) becameitems.Any(). Expected:items.Any(x => f(x) && g(x)).items.Where(x => x > 10).FirstOrDefault(5)was reported and fixed toitems.FirstOrDefault().FirstOrDefault/LastOrDefault/SingleOrDefault(defaultValue)is not a predicate overload. Expected: no diagnostic.xfor a method group:items.Where(Filter).Any(item => item > 0)becameitems.Any(item => Filter(x) && item > 0). Expected:items.Any(item => Filter(item) && item > 0).Wherewas checked for the indexed overload:items.Where(x => x > 0).Where((x, i) => i % 2 == 0)was reported and fixed to broken code. Expected: no diagnostic.GetParentLinqOperationfollowed any argument, soseqs.FirstOrDefault(items.Where(x => x > 0))reported "Combine 'Where' with 'FirstOrDefault'". Expected: no diagnostic.bool M(int[] items, int x) => items.Where(x => x > 0).Any(y => y > x)becameitems.Any(x => x > 0 && x > x). It also produced invalid code for block-bodied lambdas.MA0030 (Remove useless OrderBy call)
items.OrderBy(x => -x).Order()was fixed toitems.OrderBy(x => -x).ThenBy(), which has no key selector. Expected:ThenBy(x => x)(andThenByDescending(x => x)forOrderDescending).MA0159 (Use Order)
Enumerable.OrderBy(items, x => x)becameEnumerable.Order(x => x). Expected:Enumerable.Order(items).MA0020 (Use direct methods)
Enumerable.Count(items)(withint[] items) becameEnumerable.Length. Expected:items.Length.list?.Count()registered a fix that did nothing. Expected:list?.Count.MA0112 (Use Count > 0 instead of Any())
.Counton arrays, where it is an explicit implementation:int[] items; items.Any()becameitems.Count != 0(CS1061). Expected:items.Length != 0. The doc example had the same mistake.ICollection<T>.Countexplicitly was reported, and the fix couldn't compile.Enumerable.Any(items)wasn't fixed toitems.Count != 0, anditems?.Any()got a fix that produced invalid code.MA0078 (Use Cast instead of Select)
items.Select(x => (long?)x)and, withenum E : byte,items.Select(x => (E)x)onint[] itemswere reported and fixed toCast<long?>()/Cast<E>(), which throwInvalidCastException.MA0098 / MA0020 on interface-typed receivers
IList<int> a; ICollection<int> b; IReadOnlyList<int> c; a.First(); b.Count(); c.Last(); a.Count();gave no diagnostic.AllInterfacesdoesn't include the type itself, andGetMembers("Count")doesn't return inherited members (so a class deriving fromList<T>wasn't reported either). Expected: 4 diagnostics.Fix
Analyzer:
IsPredicateOverloadcheck, based on the original definition of the method, for both theWhereand the next method. The next method must take only the source, or the source and a non-indexed predicate.GetParentLinqOperationonly follows the first (this) argument of an extension method.CanReplaceByCastuses the C# conversion classification. It accepts identity, reference, boxing and unboxing conversions, and nullable/enum conversions only when the unboxing types match (the enum underlying type, withoutNullable<T>). These are the conversions thatCast<T>(unbox/castclass of the boxed value) supports.GetAllInterfacesIncludingSelf).Countand theintindexer are resolved withSemanticModel.LookupSymbols, which handles inherited and base-interface members and excludes explicit implementations. A diagnostic is reported only when the member lookup finds exactly one accessible member. This also rules out ambiguous interfaces such asinterface IMyList : IList<int>, IReadOnlyList<int>. Arrays still useLength.Fixer (every precondition is now checked before
RegisterCodeFix):Filter(x)), or from delegate locals, parameters and fields (f(x)). The parameter name is the first lambda parameter name that doesn't conflict with an identifier of the other predicate. Otherwise it'sx,x1, … not in scope. No fix is offered for block-bodied lambdas or for delegates/instances that can't be safely evaluated once per element (e.g.Where(GetFilter())).ThenBy(x => x)/ThenByDescending(x => x)when the second call isOrder()/OrderDescending(), with a parameter name that isn't in scope.CreatePropertyAccesshandlesitems.Count(),Enumerable.Count(items)anditems?.Count(). For MA0112,items?.Any()is not fixed, and arrays useLength.Docs: fixed the MA0112 example. MA0029, MA0030 and MA0078 now describe the new behavior.
Tests
Added regression tests to
OptimizeLinqUsageAnalyzerTests(code-fix tests for every sub-bug, plus no-diagnostic/no-fix tests). Existing tests were not changed. The fullOptimizeLinqUsageAnalyzerTestsclass passes on roslyn5.9 (203/203) and roslyn4.8 (203/203). The code fixers build without warnings for roslyn4.14, 5.0 and 5.6.DocumentationGeneratorreports no pending change.