Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CA1860: Avoid using 'Enumerable.Any()' extension method #2196

Merged
merged 4 commits into from
May 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,8 @@ dotnet_diagnostic.CA1724.severity = none
dotnet_diagnostic.CA1819.severity = none
# CA1851: Possible multiple enumerations of IEnumerable collection. Related to GH-issue #2000
dotnet_diagnostic.CA1851.severity = suggestion
# CA1860: Avoid using 'Enumerable.Any()' extension method
dotnet_diagnostic.CA1860.severity = warning
# CA2007: Do not directly await a Task
dotnet_diagnostic.CA2007.severity = none
# CA2225: Operator overloads have named alternates
Expand Down
16 changes: 8 additions & 8 deletions Src/FluentAssertions/Collections/GenericCollectionAssertions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -896,7 +896,7 @@ public AndConstraint<TAssertions> Contain(IEnumerable<T> expected, string becaus

string[] failures = scope.Discard();

if (!failures.Any())
if (failures.Length == 0)
{
return new AndWhichConstraint<TAssertions, T>((TAssertions)this, actualItem);
}
Expand Down Expand Up @@ -1156,7 +1156,7 @@ public AndConstraint<TAssertions> ContainItemsAssignableTo<TExpectation>(string
ICollection<T> actualItems = Subject.ConvertOrCastToCollection();

Execute.Assertion
.ForCondition(actualItems.Any())
.ForCondition(actualItems.Count > 0)
.BecauseOf(because, becauseArgs)
.FailWith(expectationPrefix + "but the collection is empty.", predicate);

Expand Down Expand Up @@ -2336,7 +2336,7 @@ public AndConstraint<TAssertions> NotContain(IEnumerable<T> unexpected, string b

string[] failures = scope.Discard();

if (!failures.Any())
if (failures.Length == 0)
{
foundIndices.Add(index);
}
Expand Down Expand Up @@ -2786,7 +2786,7 @@ public AndConstraint<TAssertions> NotHaveCount(int unexpected, string because =
.FailWith("but the collection is <null>.")
.Then
.Given(subject => subject.ConvertOrCastToCollection())
.ForCondition(collection => collection.Any())
.ForCondition(collection => collection.Count > 0)
.FailWith("but the collection is empty.")
.Then
.Given(collection => collection.Where(item => !compiledPredicate(item)))
Expand Down Expand Up @@ -2943,7 +2943,7 @@ public AndConstraint<TAssertions> AllSatisfy(Action<T> expected, string because
failuresFromInspectors = CollectFailuresFromInspectors(elementInspectors);
}

if (failuresFromInspectors.Any())
if (failuresFromInspectors.Length > 0)
{
string failureMessage = Environment.NewLine
+ string.Join(Environment.NewLine, failuresFromInspectors.Select(x => x.IndentLines()));
Expand Down Expand Up @@ -3031,7 +3031,7 @@ public AndConstraint<TAssertions> SatisfyRespectively(params Action<T>[] element
failuresFromInspectors = CollectFailuresFromInspectors(elementInspectors);
}

if (failuresFromInspectors.Any())
if (failuresFromInspectors.Length > 0)
{
string failureMessage = Environment.NewLine
+ string.Join(Environment.NewLine, failuresFromInspectors.Select(x => x.IndentLines()));
Expand Down Expand Up @@ -3114,7 +3114,7 @@ public AndConstraint<TAssertions> Satisfy(params Expression<Func<T, bool>>[] pre

List<MaximumMatching.Predicate<T>> unmatchedPredicates = maximumMatchingSolution.GetUnmatchedPredicates();

if (unmatchedPredicates.Any())
if (unmatchedPredicates.Count > 0)
{
message += doubleNewLine + "The following predicates did not have matching elements:";

Expand All @@ -3125,7 +3125,7 @@ public AndConstraint<TAssertions> Satisfy(params Expression<Func<T, bool>>[] pre

List<Element<T>> unmatchedElements = maximumMatchingSolution.GetUnmatchedElements();

if (unmatchedElements.Any())
if (unmatchedElements.Count > 0)
{
message += doubleNewLine + "The following elements did not match any predicate:";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -720,7 +720,7 @@ public AndConstraint<TAssertions> Contain(params KeyValuePair<TKey, TValue>[] ex
KeyValuePair<TKey, TValue>[] keyValuePairsNotSameOrEqualInSubject = expectedKeyValuePairs
.Where(keyValuePair => !areSameOrEqual(GetValue(Subject, keyValuePair.Key), keyValuePair.Value)).ToArray();

if (keyValuePairsNotSameOrEqualInSubject.Any())
if (keyValuePairsNotSameOrEqualInSubject.Length > 0)
{
if (keyValuePairsNotSameOrEqualInSubject.Length > 1)
{
Expand Down Expand Up @@ -865,14 +865,14 @@ public AndConstraint<TAssertions> NotContain(params KeyValuePair<TKey, TValue>[]
KeyValuePair<TKey, TValue>[] keyValuePairsFound =
keyValuePairs.Where(keyValuePair => ContainsKey(Subject, keyValuePair.Key)).ToArray();

if (keyValuePairsFound.Any())
if (keyValuePairsFound.Length > 0)
{
Func<TValue, TValue, bool> areSameOrEqual = ObjectExtensions.GetComparer<TValue>();

KeyValuePair<TKey, TValue>[] keyValuePairsSameOrEqualInSubject = keyValuePairsFound
.Where(keyValuePair => areSameOrEqual(GetValue(Subject, keyValuePair.Key), keyValuePair.Value)).ToArray();

if (keyValuePairsSameOrEqualInSubject.Any())
if (keyValuePairsSameOrEqualInSubject.Length > 0)
{
if (keyValuePairsSameOrEqualInSubject.Length > 1)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ private bool ContainsMatch(string wildcardPattern)
return Subject.Any(item =>
{
item.Should().Match(wildcardPattern);
return !scope.Discard().Any();
return scope.Discard().Length == 0;
});
}

Expand All @@ -285,7 +285,7 @@ private IEnumerable<string> AllThatMatch(string wildcardPattern)
{
using var scope = new AssertionScope();
item.Should().Match(wildcardPattern);
return !scope.Discard().Any();
return scope.Discard().Length == 0;
});
}

Expand Down Expand Up @@ -357,7 +357,7 @@ private bool NotContainsMatch(string wildcardPattern)
return Subject.All(item =>
{
item.Should().NotMatch(wildcardPattern);
return !scope.Discard().Any();
return scope.Discard().Length == 0;
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ private static void CompareConstraintColumns(DataColumn[] subjectColumns, DataCo

var failureMessage = new StringBuilder();

if (missingColumnNames.Any())
if (missingColumnNames.Count > 0)
{
failureMessage.Append("Expected {context:constraint} to include ");

Expand All @@ -232,7 +232,7 @@ private static void CompareConstraintColumns(DataColumn[] subjectColumns, DataCo
: "these columns. ");
}

if (extraColumnNames.Any())
if (extraColumnNames.Count > 0)
{
failureMessage.Append("Did not expect {context:constraint} to include ");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ private static bool AssertSubjectIsNotNull(object subject)
KeyDifference<TSubjectKey, TExpectedKey> keyDifference = CalculateKeyDifference(subject, expectation);

bool hasMissingKeys = keyDifference.MissingKeys.Count > 0;
bool hasAdditionalKeys = keyDifference.AdditionalKeys.Any();
bool hasAdditionalKeys = keyDifference.AdditionalKeys.Count > 0;

Execute.Assertion
.WithExpectation("Expected {context:subject} to be a dictionary with {0} item(s){reason}, ", expectation.Count)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ private static bool IsGenericCollection(Type type)
{
Type[] enumerableInterfaces = GetIEnumerableInterfaces(type);

return !typeof(string).IsAssignableFrom(type) && enumerableInterfaces.Any();
return !typeof(string).IsAssignableFrom(type) && enumerableInterfaces.Length > 0;
}

private static Type[] GetIEnumerableInterfaces(Type type)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public class StructuralEqualityEquivalencyStep : IEquivalencyStep
{
IMember[] selectedMembers = GetMembersFromExpectation(context.CurrentNode, comparands, context.Options).ToArray();

if (context.CurrentNode.IsRoot && !selectedMembers.Any())
if (context.CurrentNode.IsRoot && selectedMembers.Length == 0)
{
throw new InvalidOperationException(
"No members were found for comparison. " +
Expand Down
10 changes: 5 additions & 5 deletions Src/FluentAssertions/EventRaisingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public static IEventRecording WithSender(this IEventRecording eventRecording, ob
foreach (OccurredEvent @event in eventRecording)
{
bool hasSender = Execute.Assertion
.ForCondition(@event.Parameters.Any())
.ForCondition(@event.Parameters.Length > 0)
.FailWith("Expected event from sender {0}, " +
$"but event {eventRecording.EventName} does not have any parameters", expectedSender);

Expand All @@ -47,7 +47,7 @@ public static IEventRecording WithSender(this IEventRecording eventRecording, ob
}

Execute.Assertion
.ForCondition(eventsForSender.Any())
.ForCondition(eventsForSender.Count > 0)
.FailWith("Expected sender {0}, but found {1}.",
() => expectedSender,
() => otherSenders.Distinct());
Expand Down Expand Up @@ -81,7 +81,7 @@ public static IEventRecording WithArgs<T>(this IEventRecording eventRecording, E
}
}

bool foundMatchingEvent = eventsWithMatchingPredicate.Any();
bool foundMatchingEvent = eventsWithMatchingPredicate.Count > 0;

Execute.Assertion
.ForCondition(foundMatchingEvent)
Expand Down Expand Up @@ -111,7 +111,7 @@ public static IEventRecording WithArgs<T>(this IEventRecording eventRecording, p
foreach (OccurredEvent @event in eventRecording)
{
var typedParameters = @event.Parameters.OfType<T>().ToArray();
bool hasArgumentOfRightType = typedParameters.Any();
bool hasArgumentOfRightType = typedParameters.Length > 0;

if (predicates.Length > typedParameters.Length)
{
Expand All @@ -132,7 +132,7 @@ public static IEventRecording WithArgs<T>(this IEventRecording eventRecording, p
}
}

bool foundMatchingEvent = eventsWithMatchingPredicate.Any();
bool foundMatchingEvent = eventsWithMatchingPredicate.Count > 0;

if (!foundMatchingEvent)
{
Expand Down
2 changes: 1 addition & 1 deletion Src/FluentAssertions/Events/EventMonitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ private void Attach(Type typeDefiningEventsToMonitor, Func<DateTime> utcNow)

EventInfo[] events = GetPublicEvents(typeDefiningEventsToMonitor);

if (!events.Any())
if (events.Length == 0)
{
throw new InvalidOperationException($"Type {typeDefiningEventsToMonitor.Name} does not expose any events.");
}
Expand Down
2 changes: 1 addition & 1 deletion Src/FluentAssertions/Execution/AssertionScope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ public AssertionScope BecauseOf(string because, params object[] becauseArgs)
{
string becauseOrEmpty = because ?? string.Empty;

return becauseArgs?.Any() == true
return becauseArgs?.Length > 0
? string.Format(CultureInfo.InvariantCulture, becauseOrEmpty, becauseArgs)
: becauseOrEmpty;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public IEnumerable<string> DiscardFailures()
/// </summary>
public void ThrowIfAny(IDictionary<string, object> context)
{
if (failureMessages.Any())
if (failureMessages.Count > 0)
{
var builder = new StringBuilder();
builder.AppendJoin(Environment.NewLine, failureMessages).AppendLine();
Expand Down
2 changes: 1 addition & 1 deletion Src/FluentAssertions/Formatting/TimeSpanValueFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public void Format(object value, FormattedObjectGraph formattedGraph, Formatting

List<string> fragments = GetNonZeroFragments(timeSpan);

if (!fragments.Any())
if (fragments.Count == 0)
{
formattedGraph.AddFragment("default");
}
Expand Down
2 changes: 1 addition & 1 deletion Src/FluentAssertions/Primitives/StringAssertions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ public AndConstraint<TAssertions> BeOneOf(IEnumerable<string> validValues, strin
using (var scope = new AssertionScope())
{
Subject.Should().BeEquivalentTo(unexpected);
notEquivalent = scope.Discard().Any();
notEquivalent = scope.Discard().Length > 0;
}

Execute.Assertion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ public AsyncFunctionAssertions(Func<TTask> subject, IExtractExceptions extractor
.ForCondition(exception is not null)
.FailWith("but no exception was thrown.")
.Then
.ForCondition(expectedExceptions.Any())
.ForCondition(expectedExceptions.Length > 0)
.FailWith("but found <{0}>:" + Environment.NewLine + "{1}.",
exception?.GetType(),
exception)
Expand Down
2 changes: 1 addition & 1 deletion Src/FluentAssertions/Specialized/DelegateAssertionsBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ private protected DelegateAssertionsBase(TDelegate @delegate, IExtractExceptions
.ForCondition(exception is not null)
.FailWith("but no exception was thrown.")
.Then
.ForCondition(expectedExceptions.Any())
.ForCondition(expectedExceptions.Length > 0)
.FailWith("but found <{0}>:" + Environment.NewLine + "{1}.",
exception?.GetType(),
exception)
Expand Down
4 changes: 2 additions & 2 deletions Src/FluentAssertions/Specialized/ExceptionAssertions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ public ExceptionAssertions(IEnumerable<TException> exceptions)
.Where(e => e?.GetType() == innerException).ToArray();

Execute.Assertion
.ForCondition(expectedExceptions.Any())
.ForCondition(expectedExceptions.Length > 0)
.BecauseOf(because, becauseArgs)
.FailWith("Expected inner {0}{reason}, but found {1}.", innerException, SingleSubject.InnerException);

Expand All @@ -233,7 +233,7 @@ public ExceptionAssertions(IEnumerable<TException> exceptions)
.ToArray();

Execute.Assertion
.ForCondition(expectedInnerExceptions.Any())
.ForCondition(expectedInnerExceptions.Length > 0)
.BecauseOf(because, becauseArgs)
.FailWith("Expected inner {0}{reason}, but found {1}.", innerException, SingleSubject.InnerException);

Expand Down
16 changes: 8 additions & 8 deletions Src/FluentAssertions/Types/MethodInfoSelectorAssertions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public AndConstraint<MethodInfoSelectorAssertions> BeVirtual(string because = ""
GetDescriptionsFor(nonVirtualMethods);

Execute.Assertion
.ForCondition(!nonVirtualMethods.Any())
.ForCondition(nonVirtualMethods.Length == 0)
.BecauseOf(because, becauseArgs)
.FailWith(failureMessage);

Expand All @@ -81,7 +81,7 @@ public AndConstraint<MethodInfoSelectorAssertions> NotBeVirtual(string because =
GetDescriptionsFor(virtualMethods);

Execute.Assertion
.ForCondition(!virtualMethods.Any())
.ForCondition(virtualMethods.Length == 0)
.BecauseOf(because, becauseArgs)
.FailWith(failureMessage);

Expand Down Expand Up @@ -118,7 +118,7 @@ public AndConstraint<MethodInfoSelectorAssertions> BeAsync(string because = "",
GetDescriptionsFor(nonAsyncMethods);

Execute.Assertion
.ForCondition(!nonAsyncMethods.Any())
.ForCondition(nonAsyncMethods.Length == 0)
.BecauseOf(because, becauseArgs)
.FailWith(failureMessage);

Expand All @@ -145,7 +145,7 @@ public AndConstraint<MethodInfoSelectorAssertions> NotBeAsync(string because = "
GetDescriptionsFor(asyncMethods);

Execute.Assertion
.ForCondition(!asyncMethods.Any())
.ForCondition(asyncMethods.Length == 0)
.BecauseOf(because, becauseArgs)
.FailWith(failureMessage);

Expand Down Expand Up @@ -198,7 +198,7 @@ public AndConstraint<MethodInfoSelectorAssertions> NotBeAsync(string because = "
GetDescriptionsFor(methodsWithoutAttribute);

Execute.Assertion
.ForCondition(!methodsWithoutAttribute.Any())
.ForCondition(methodsWithoutAttribute.Length == 0)
.BecauseOf(because, becauseArgs)
.FailWith(failureMessage, typeof(TAttribute));

Expand Down Expand Up @@ -251,7 +251,7 @@ public AndConstraint<MethodInfoSelectorAssertions> NotBeAsync(string because = "
GetDescriptionsFor(methodsWithAttribute);

Execute.Assertion
.ForCondition(!methodsWithAttribute.Any())
.ForCondition(methodsWithAttribute.Length == 0)
.BecauseOf(because, becauseArgs)
.FailWith(failureMessage, typeof(TAttribute));

Expand All @@ -278,7 +278,7 @@ public AndConstraint<MethodInfoSelectorAssertions> NotBeAsync(string because = "
Environment.NewLine + GetDescriptionsFor(methods);

Execute.Assertion
.ForCondition(!methods.Any())
.ForCondition(methods.Length == 0)
.BecauseOf(because, becauseArgs)
.FailWith(message);

Expand All @@ -305,7 +305,7 @@ public AndConstraint<MethodInfoSelectorAssertions> NotBeAsync(string because = "
Environment.NewLine + GetDescriptionsFor(methods);

Execute.Assertion
.ForCondition(!methods.Any())
.ForCondition(methods.Length == 0)
.BecauseOf(because, becauseArgs)
.FailWith(message);

Expand Down