Enable CA1868: Unnecessary call to 'Contains' for sets (#21165)

https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1868
This commit is contained in:
xtqqczze 2024-02-29 17:56:22 +00:00 committed by GitHub
parent f8ca532dd7
commit 0e106faafe
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 26 additions and 65 deletions

View File

@ -510,6 +510,10 @@ dotnet_diagnostic.CA1846.severity = warning
# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1847 # https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1847
dotnet_diagnostic.CA1847.severity = warning dotnet_diagnostic.CA1847.severity = warning
# CA1868: Unnecessary call to 'Contains' for sets
# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1868
dotnet_diagnostic.CA1868.severity = warning
# CA2000: Dispose objects before losing scope # CA2000: Dispose objects before losing scope
# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2000 # https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2000
dotnet_diagnostic.CA2000.severity = none dotnet_diagnostic.CA2000.severity = none

View File

@ -535,9 +535,8 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets
{ {
if (this.curCimSessionsById.ContainsKey(id)) if (this.curCimSessionsById.ContainsKey(id))
{ {
if (!sessionIds.Contains(id)) if (sessionIds.Add(id))
{ {
sessionIds.Add(id);
sessions.Add(this.curCimSessionsById[id].GetPSObject()); sessions.Add(this.curCimSessionsById[id].GetPSObject());
} }
} }

View File

@ -81,9 +81,8 @@ namespace Microsoft.PowerShell.Commands
foreach (string memberName in Enum.GetNames(accessRightType)) foreach (string memberName in Enum.GetNames(accessRightType))
{ {
int memberValue = (int)Enum.Parse(accessRightType, memberName); int memberValue = (int)Enum.Parse(accessRightType, memberName);
if (!foundAccessRightValues.Contains(memberValue)) if (foundAccessRightValues.Add(memberValue))
{ {
foundAccessRightValues.Add(memberValue);
if ((accessMask & memberValue) == memberValue) if ((accessMask & memberValue) == memberValue)
{ {
foundAccessRightNames.Add(memberName); foundAccessRightNames.Add(memberName);

View File

@ -1419,11 +1419,7 @@ namespace Microsoft.PowerShell.Commands
{ {
if (!string.IsNullOrEmpty(currentHeader)) if (!string.IsNullOrEmpty(currentHeader))
{ {
if (!headers.Contains(currentHeader)) if (!headers.Add(currentHeader))
{
headers.Add(currentHeader);
}
else
{ {
// throw a terminating error as there are duplicate headers in the input. // throw a terminating error as there are duplicate headers in the input.
string memberAlreadyPresentMsg = string memberAlreadyPresentMsg =

View File

@ -792,9 +792,8 @@ namespace Microsoft.PowerShell.Commands
if (ShouldProcess(formattedTarget, action)) if (ShouldProcess(formattedTarget, action))
{ {
if (!fullFileNameHash.Contains(resolvedPath)) if (fullFileNameHash.Add(resolvedPath))
{ {
fullFileNameHash.Add(resolvedPath);
newTypes.Add(new SessionStateTypeEntry(prependPathTotal[i])); newTypes.Add(new SessionStateTypeEntry(prependPathTotal[i]));
} }
} }
@ -806,9 +805,8 @@ namespace Microsoft.PowerShell.Commands
if (entry.FileName != null) if (entry.FileName != null)
{ {
string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(entry.FileName, Context) ?? entry.FileName; string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(entry.FileName, Context) ?? entry.FileName;
if (!fullFileNameHash.Contains(resolvedPath)) if (fullFileNameHash.Add(resolvedPath))
{ {
fullFileNameHash.Add(resolvedPath);
newTypes.Add(entry); newTypes.Add(entry);
} }
} }
@ -825,9 +823,8 @@ namespace Microsoft.PowerShell.Commands
if (ShouldProcess(formattedTarget, action)) if (ShouldProcess(formattedTarget, action))
{ {
if (!fullFileNameHash.Contains(resolvedPath)) if (fullFileNameHash.Add(resolvedPath))
{ {
fullFileNameHash.Add(resolvedPath);
newTypes.Add(new SessionStateTypeEntry(appendPathTotalItem)); newTypes.Add(new SessionStateTypeEntry(appendPathTotalItem));
} }
} }
@ -971,9 +968,8 @@ namespace Microsoft.PowerShell.Commands
if (ShouldProcess(formattedTarget, action)) if (ShouldProcess(formattedTarget, action))
{ {
if (!fullFileNameHash.Contains(appendPathTotalItem)) if (fullFileNameHash.Add(appendPathTotalItem))
{ {
fullFileNameHash.Add(appendPathTotalItem);
newFormats.Add(new SessionStateFormatEntry(appendPathTotalItem)); newFormats.Add(new SessionStateFormatEntry(appendPathTotalItem));
} }
} }

View File

@ -601,8 +601,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
// if it is a type reference, just add the type name // if it is a type reference, just add the type name
if (r is TypeReference tr) if (r is TypeReference tr)
{ {
if (!allTypes.Contains(tr.name)) allTypes.Add(tr.name);
allTypes.Add(tr.name);
} }
else else
{ {
@ -619,8 +618,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
// we found the group, go over it // we found the group, go over it
foreach (TypeReference x in tgd.typeReferenceList) foreach (TypeReference x in tgd.typeReferenceList)
{ {
if (!allTypes.Contains(x.name)) allTypes.Add(x.name);
allTypes.Add(x.name);
} }
} }
} }

View File

@ -1151,10 +1151,8 @@ namespace System.Management.Automation
case "ActivePostCommand": currentActionSet = _activePostCommand; break; case "ActivePostCommand": currentActionSet = _activePostCommand; break;
} }
if (currentActionSet.Contains(command)) if (!currentActionSet.Add(command))
throw new InvalidOperationException(); throw new InvalidOperationException();
else
currentActionSet.Add(command);
} }
internal void UnregisterLookupCommandInfoAction(string currentAction, string command) internal void UnregisterLookupCommandInfoAction(string currentAction, string command)
@ -1168,8 +1166,7 @@ namespace System.Management.Automation
case "ActivePostCommand": currentActionSet = _activePostCommand; break; case "ActivePostCommand": currentActionSet = _activePostCommand; break;
} }
if (currentActionSet.Contains(command)) currentActionSet.Remove(command);
currentActionSet.Remove(command);
} }
private readonly HashSet<string> _activePreLookup = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private readonly HashSet<string> _activePreLookup = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

View File

@ -1569,14 +1569,10 @@ namespace System.Management.Automation.Runspaces
string assembly = ss.Assemblies[i].FileName; string assembly = ss.Assemblies[i].FileName;
if (!string.IsNullOrEmpty(assembly)) if (!string.IsNullOrEmpty(assembly))
{ {
if (assemblyList.Contains(assembly)) if (!assemblyList.Add(assembly))
{ {
ss.Assemblies.RemoveItem(i); ss.Assemblies.RemoveItem(i);
} }
else
{
assemblyList.Add(assembly);
}
} }
} }

View File

@ -1047,9 +1047,8 @@ namespace Microsoft.PowerShell.Commands
PSModuleInfo module = CreateModuleInfoForGetModule(resolvedModulePath, refresh); PSModuleInfo module = CreateModuleInfoForGetModule(resolvedModulePath, refresh);
if (module != null) if (module != null)
{ {
if (!modules.Contains(resolvedModulePath)) if (modules.Add(resolvedModulePath))
{ {
modules.Add(resolvedModulePath);
yield return module; yield return module;
} }
} }
@ -1078,9 +1077,8 @@ namespace Microsoft.PowerShell.Commands
foundModule = true; foundModule = true;
// We need to list all versions of the module. // We need to list all versions of the module.
string subModulePath = Path.GetDirectoryName(file); string subModulePath = Path.GetDirectoryName(file);
if (!modules.Contains(subModulePath)) if (modules.Add(subModulePath))
{ {
modules.Add(subModulePath);
yield return module; yield return module;
} }
} }

View File

@ -1321,9 +1321,8 @@ namespace System.Management.Automation.Language
foreach (var typeDefinitionAst in typeDefinitions) foreach (var typeDefinitionAst in typeDefinitions)
{ {
var typeName = GetClassNameInAssembly(typeDefinitionAst); var typeName = GetClassNameInAssembly(typeDefinitionAst);
if (!definedTypes.Contains(typeName)) if (definedTypes.Add(typeName))
{ {
definedTypes.Add(typeName);
if ((typeDefinitionAst.TypeAttributes & TypeAttributes.Class) == TypeAttributes.Class) if ((typeDefinitionAst.TypeAttributes & TypeAttributes.Class) == TypeAttributes.Class)
{ {
defineTypeHelpers.Add(new DefineTypeHelper(parser, module, typeDefinitionAst, typeName)); defineTypeHelpers.Add(new DefineTypeHelper(parser, module, typeDefinitionAst, typeName));

View File

@ -90,17 +90,13 @@ namespace System.Management.Automation.Language
foreach (var parameter in parameters) foreach (var parameter in parameters)
{ {
string parameterName = parameter.Name.VariablePath.UserPath; string parameterName = parameter.Name.VariablePath.UserPath;
if (parametersSet.Contains(parameterName)) if (!parametersSet.Add(parameterName))
{ {
_parser.ReportError(parameter.Name.Extent, _parser.ReportError(parameter.Name.Extent,
nameof(ParserStrings.DuplicateFormalParameter), nameof(ParserStrings.DuplicateFormalParameter),
ParserStrings.DuplicateFormalParameter, ParserStrings.DuplicateFormalParameter,
parameterName); parameterName);
} }
else
{
parametersSet.Add(parameterName);
}
var voidConstraint = var voidConstraint =
parameter.Attributes.OfType<TypeConstraintAst>().FirstOrDefault(static t => typeof(void) == t.TypeName.GetReflectionType()); parameter.Attributes.OfType<TypeConstraintAst>().FirstOrDefault(static t => typeof(void) == t.TypeName.GetReflectionType());
@ -242,7 +238,7 @@ namespace System.Management.Automation.Language
foreach (var namedArg in attributeAst.NamedArguments) foreach (var namedArg in attributeAst.NamedArguments)
{ {
string name = namedArg.ArgumentName; string name = namedArg.ArgumentName;
if (names.Contains(name)) if (!names.Add(name))
{ {
_parser.ReportError(namedArg.Extent, _parser.ReportError(namedArg.Extent,
nameof(ParserStrings.DuplicateNamedArgument), nameof(ParserStrings.DuplicateNamedArgument),
@ -251,8 +247,6 @@ namespace System.Management.Automation.Language
} }
else else
{ {
names.Add(name);
if (!namedArg.ExpressionOmitted && !IsValidAttributeArgument(namedArg.Argument, constantValueVisitor)) if (!namedArg.ExpressionOmitted && !IsValidAttributeArgument(namedArg.Argument, constantValueVisitor))
{ {
var error = GetNonConstantAttributeArgErrorExpr(constantValueVisitor); var error = GetNonConstantAttributeArgErrorExpr(constantValueVisitor);
@ -1124,7 +1118,7 @@ namespace System.Management.Automation.Language
if (keyStrAst != null) if (keyStrAst != null)
{ {
var keyStr = keyStrAst.Value.ToString(); var keyStr = keyStrAst.Value.ToString();
if (keys.Contains(keyStr)) if (!keys.Add(keyStr))
{ {
string errorId; string errorId;
string errorMsg; string errorMsg;
@ -1141,10 +1135,6 @@ namespace System.Management.Automation.Language
_parser.ReportError(entry.Item1.Extent, errorId, errorMsg, keyStr); _parser.ReportError(entry.Item1.Extent, errorId, errorMsg, keyStr);
} }
else
{
keys.Add(keyStr);
}
} }
} }

View File

@ -797,10 +797,7 @@ namespace System.Management.Automation.Internal
return; return;
} }
if (_preparingForDisconnectList.Contains(bcmdTM)) _preparingForDisconnectList.Remove(bcmdTM);
{
_preparingForDisconnectList.Remove(bcmdTM);
}
if (_preparingForDisconnectList.Count == 0) if (_preparingForDisconnectList.Count == 0)
{ {

View File

@ -1081,10 +1081,7 @@ namespace System.Management.Automation
{ {
// this command is not visible to the user (from CommandOrigin) so // this command is not visible to the user (from CommandOrigin) so
// dont show help topic for it. // dont show help topic for it.
if (!hiddenCommands.Contains(helpName)) hiddenCommands.Add(helpName);
{
hiddenCommands.Add(helpName);
}
continue; continue;
} }

View File

@ -170,11 +170,7 @@ namespace System.Management.Automation
{ {
string fileName = Path.GetFileName(file); string fileName = Path.GetFileName(file);
if (!fileNameHash.Contains(fileName)) if (!fileNameHash.Add(fileName))
{
fileNameHash.Add(fileName);
}
else
{ {
// If the file need to be removed, add it to matchedFilesToRemove, if not already present. // If the file need to be removed, add it to matchedFilesToRemove, if not already present.
if (!matchedFilesToRemove.Contains(file)) if (!matchedFilesToRemove.Contains(file))

View File

@ -220,9 +220,8 @@ namespace System.Management.Automation
relativePath = fileToHash.Name; relativePath = fileToHash.Name;
} }
if (!relativePaths.Contains(relativePath)) if (relativePaths.Add(relativePath))
{ {
relativePaths.Add(relativePath);
if (fileToHash.Length != 0) if (fileToHash.Length != 0)
{ {
cdfFilesContent += "<HASH>" + fileToHash.FullName + "=" + fileToHash.FullName + Environment.NewLine; cdfFilesContent += "<HASH>" + fileToHash.FullName + "=" + fileToHash.FullName + Environment.NewLine;