Uh oh!
There was an error while loading. Please reload this page.
C#: Missed FirstOrDefault query. - #22497
Conversation
Co-authored-by: Michael Nebel <michaelnebel@github.com>
Co-authored-by: Michael Nebel <michaelnebel@github.com>
QHelp previews: csharp/ql/src/Linq/MissedFirstOrDefaultOpportunity.qhelpMissed opportunity to use FirstOrDefaultProgrammers sometimes search a sequence by iterating over each element, testing it, and returning the first element that satisfies the test. If the loop completes without finding a match, the method then returns a default value such as RecommendationThis pattern is directly available as the ExampleIn this example the method searches a list of operations for the first operation with a matching identifier, returning usingSystem;usingSystem.Collections.Generic;classMissedFirstOrDefaultOpportunity{publicstaticOperationFindOperation(IEnumerable<Operation>operations,stringoperationId){foreach(varoperationinoperations){if(string.Equals(operation.OperationId,operationId,StringComparison.Ordinal))returnoperation;}returnnull;}}classOperation{publicstringOperationId{get;set;}}The LINQ usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;classMissedFirstOrDefaultOpportunityFix{publicstaticOperationFindOperation(IEnumerable<Operation>operations,stringoperationId){returnoperations.FirstOrDefault(operation =>string.Equals(operation.OperationId,operationId,StringComparison.Ordinal));}}The following examples should not use usingSystem;usingSystem.Collections.Generic;classMissedFirstOrDefaultOpportunityGood{publicstaticOperationFindOperationOrThrow(IEnumerable<Operation>operations,stringoperationId){foreach(varoperationinoperations){if(string.Equals(operation.OperationId,operationId,StringComparison.Ordinal))thrownewInvalidOperationException("Unexpected operation.");}returnnull;}publicstaticOperationFindReplacementOperation(IEnumerable<Operation>operations,stringoperationId){foreach(varoperationinoperations){if(string.Equals(operation.OperationId,operationId,StringComparison.Ordinal))returnoperation;}returnnewOperation();}publicstaticstringFindOperationId(IEnumerable<Operation>operations,stringoperationId){foreach(varoperationinoperations){if(string.Equals(operation.OperationId,operationId,StringComparison.Ordinal))returnoperation.OperationId;}returnnull;}}References |
No description provided.