Code performance fixes (#12956)

* RCS1080: Use 'Count/Length' property instead of 'Any' method

* RCS1077: Optimize LINQ method call

* RCS1235: Optimize method call
This commit is contained in:
xtqqczze 2020-06-25 07:30:40 +01:00 committed by GitHub
parent bf3b48db13
commit bd90f1921f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
71 changed files with 182 additions and 185 deletions

View file

@ -234,8 +234,8 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets
CimSetCimInstanceContext setContext = context as CimSetCimInstanceContext;
if (setContext != null)
{
if ((string.Compare(setContext.ParameterSetName, CimBaseCommand.QueryComputerSet, StringComparison.OrdinalIgnoreCase) == 0) ||
(string.Compare(setContext.ParameterSetName, CimBaseCommand.QuerySessionSet, StringComparison.OrdinalIgnoreCase) == 0))
if (string.Equals(setContext.ParameterSetName, CimBaseCommand.QueryComputerSet, StringComparison.OrdinalIgnoreCase) ||
string.Equals(setContext.ParameterSetName, CimBaseCommand.QuerySessionSet, StringComparison.OrdinalIgnoreCase))
{
this.setCimInstance.SetCimInstance(sendToPipeline as CimInstance, setContext, this);
return;

View file

@ -452,7 +452,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets
foreach (string propertyName in value)
{
// * is wild char supported in select properties
if ((propertyName != null) && (string.Compare(propertyName.Trim(), "*", StringComparison.OrdinalIgnoreCase) == 0))
if ((propertyName != null) && string.Equals(propertyName.Trim(), "*", StringComparison.OrdinalIgnoreCase))
{
continue;
}

View file

@ -82,11 +82,11 @@ namespace Microsoft.Management.UI.Internal
HelpCategory category = HelpCategory.Default;
if (string.Compare(strCategory, "DscResource", StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(strCategory, "DscResource", StringComparison.OrdinalIgnoreCase))
{
category = HelpCategory.DscResource;
}
else if (string.Compare(strCategory, "Class", StringComparison.OrdinalIgnoreCase) == 0)
else if (string.Equals(strCategory, "Class", StringComparison.OrdinalIgnoreCase))
{
category = HelpCategory.Class;
}
@ -594,7 +594,7 @@ namespace Microsoft.Management.UI.Internal
string type = GetPropertyString(member, "type");
string propertyType = null;
if (string.Compare("field", type, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals("field", type, StringComparison.OrdinalIgnoreCase))
{
PSObject fieldData = HelpParagraphBuilder.GetPropertyObject(member, "fieldData") as PSObject;
@ -610,7 +610,7 @@ namespace Microsoft.Management.UI.Internal
memberText = string.Format(CultureInfo.CurrentCulture, " [{0}] {1}\r\n", propertyType, name);
}
}
else if (string.Compare("method", type, StringComparison.OrdinalIgnoreCase) == 0)
else if (string.Equals("method", type, StringComparison.OrdinalIgnoreCase))
{
FormatMethodData(member, name, out memberText, out description);
}
@ -702,7 +702,7 @@ namespace Microsoft.Management.UI.Internal
parameterText.Append(paramString);
}
if (string.Compare(parameterText[parameterText.Length - 1].ToString(), ",", StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(parameterText[parameterText.Length - 1].ToString(), ",", StringComparison.OrdinalIgnoreCase))
{
parameterText = parameterText.Remove(parameterText.Length - 1, 1);
}

View file

@ -612,7 +612,7 @@ namespace Microsoft.PowerShell.Commands.ShowCommandInternal
}
}
return string.Compare(source.Name, target.Name, StringComparison.Ordinal);
return string.CompareOrdinal(source.Name, target.Name);
}
/// <summary>

View file

@ -276,7 +276,7 @@ namespace Microsoft.PowerShell.Commands
break;
default:
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName));
Debug.Fail(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName));
break;
}
}

View file

@ -223,7 +223,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
case BehaviorOnNoMatch.Default:
default:
return this.PropertyValueFilters
.Where(f => !f.HadMatch).Any(f => f.BehaviorOnNoMatch == BehaviorOnNoMatch.ReportErrors);
.Any(f => !f.HadMatch && f.BehaviorOnNoMatch == BehaviorOnNoMatch.ReportErrors);
}
}

View file

@ -113,7 +113,7 @@ namespace Microsoft.PowerShell.Commands
{
foreach (DriveInfo drive in _availableDrives)
{
if (string.Compare(drive.Name, drivePath, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(drive.Name, drivePath, StringComparison.OrdinalIgnoreCase))
{
actualDrive = drive;
break;

View file

@ -552,7 +552,7 @@ $result
string newLastBootUpTime = os.CimInstanceProperties["LastBootUpTime"].Value.ToString();
string oldLastBootUpTime = _computerInfos[computer].LastBootUpTime;
if (string.Compare(newLastBootUpTime, oldLastBootUpTime, StringComparison.OrdinalIgnoreCase) != 0)
if (!string.Equals(newLastBootUpTime, oldLastBootUpTime, StringComparison.OrdinalIgnoreCase))
{
_computerInfos[computer].RebootComplete = true;
nextTestList.Add(computer);

View file

@ -150,13 +150,10 @@ namespace Microsoft.PowerShell.Commands
if (_currentContentItem != null &&
((_currentContentItem.PathInfo == pathInfo) ||
(
string.Compare(
string.Equals(
pathInfo.Path,
_currentContentItem.PathInfo.Path,
StringComparison.OrdinalIgnoreCase) == 0)
)
)
StringComparison.OrdinalIgnoreCase)))
{
result = _currentContentItem.AttachNotes(result);
}

View file

@ -1042,9 +1042,9 @@ namespace Microsoft.PowerShell.Commands
// find a matching property name via case-insensitive string comparison
Predicate<string> pred = (s) =>
{
return string.Compare(s,
return string.Equals(s,
name,
StringComparison.OrdinalIgnoreCase) == 0;
StringComparison.OrdinalIgnoreCase);
};
var propertyName = availableProperties.Find(pred);

View file

@ -259,11 +259,11 @@ namespace Microsoft.PowerShell.Commands
return false;
}
return string.Compare(
return string.Equals(
SessionState.Path.GetUnresolvedProviderPathFromPSPath(breakpoint.Script),
SessionState.Path.GetUnresolvedProviderPathFromPSPath(script),
StringComparison.OrdinalIgnoreCase
) == 0;
);
});
}

View file

@ -77,7 +77,7 @@ namespace Microsoft.PowerShell.Commands
_lastObjectAsString = _lastObject.ToString();
}
if (0 == string.Compare(
if (string.Equals(
inputString,
_lastObjectAsString,
StringComparison.CurrentCulture))

View file

@ -453,7 +453,7 @@ namespace Microsoft.PowerShell.Commands
{
get
{
return string.Compare(ParameterSetName, GenericParameterSet, StringComparison.Ordinal) == 0;
return string.Equals(ParameterSetName, GenericParameterSet, StringComparison.Ordinal);
}
}

View file

@ -133,7 +133,7 @@ namespace Microsoft.PowerShell.Commands
Type type = null;
PSArgumentException mshArgE = null;
if (string.Compare(ParameterSetName, netSetName, StringComparison.Ordinal) == 0)
if (string.Equals(ParameterSetName, netSetName, StringComparison.Ordinal))
{
object _newObject = null;
try

View file

@ -231,7 +231,7 @@ namespace Microsoft.PowerShell.Commands
// Case sensitive duplicates should normally not occur since JsonConvert.DeserializeObject
// does not throw when encountering duplicates and just uses the last entry.
if (memberHashTracker.TryGetValue(entry.Key, out var maybePropertyName)
&& string.Compare(entry.Key, maybePropertyName, StringComparison.Ordinal) == 0)
&& string.Equals(entry.Key, maybePropertyName, StringComparison.Ordinal))
{
var errorMsg = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.DuplicateKeysInJsonString, entry.Key);
error = new ErrorRecord(

View file

@ -516,13 +516,13 @@ namespace Microsoft.PowerShell
if (command.Length == 2)
{
if (0 == string.Compare(command, "\"\"", StringComparison.OrdinalIgnoreCase))
if (string.Equals(command, "\"\"", StringComparison.OrdinalIgnoreCase))
{
return string.Empty;
}
}
if (0 == string.Compare(command, "$null", StringComparison.OrdinalIgnoreCase))
if (string.Equals(command, "$null", StringComparison.OrdinalIgnoreCase))
{
return null;
}

View file

@ -162,7 +162,7 @@ namespace Microsoft.PowerShell
textReader = input;
_firstLine = textReader.ReadLine();
if (string.Compare(_firstLine, Serialization.XmlCliTag, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(_firstLine, Serialization.XmlCliTag, StringComparison.OrdinalIgnoreCase))
{
// format should be XML

View file

@ -931,7 +931,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
foreach (KeyValuePair<string, DscClassCacheEntry> cimClass in ClassCache)
{
string cachedClassName = cimClass.Key.Split(Utils.Separators.Backslash)[IndexClassName];
if (string.Compare(cachedClassName, className, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(cachedClassName, className, StringComparison.OrdinalIgnoreCase))
{
return cimClass.Value.CimClassInstance;
}
@ -1107,9 +1107,9 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
let cachedClassName = splittedName[IndexClassName]
let cachedModuleName = splittedName[IndexModuleName]
let cachedResourceName = splittedName[IndexFriendlyName]
where ((string.Compare(cachedResourceName, resourceName, StringComparison.OrdinalIgnoreCase) == 0)
|| (string.Compare(cachedClassName, className, StringComparison.OrdinalIgnoreCase) == 0
&& string.Compare(cachedModuleName, moduleName, StringComparison.OrdinalIgnoreCase) == 0))
where (string.Equals(cachedResourceName, resourceName, StringComparison.OrdinalIgnoreCase)
|| (string.Equals(cachedClassName, className, StringComparison.OrdinalIgnoreCase)
&& string.Equals(cachedModuleName, moduleName, StringComparison.OrdinalIgnoreCase)))
select cacheEntry).ToList();
}
@ -1153,7 +1153,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
{
var file = pair.Key;
var classList = pair.Value;
if (classList != null && classList.FirstOrDefault((CimClass c) => string.Equals(c.CimSystemProperties.ClassName, className, StringComparison.OrdinalIgnoreCase)) != null)
if (classList != null && classList.Find((CimClass c) => string.Equals(c.CimSystemProperties.ClassName, className, StringComparison.OrdinalIgnoreCase)) != null)
{
files.Add(file);
}
@ -1553,11 +1553,11 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
private static void UpdateKnownRestriction(DynamicKeyword keyword)
{
if (
string.Compare(keyword.ResourceName, "MSFT_DSCMetaConfigurationV2",
StringComparison.OrdinalIgnoreCase) == 0
string.Equals(keyword.ResourceName, "MSFT_DSCMetaConfigurationV2",
StringComparison.OrdinalIgnoreCase)
||
string.Compare(keyword.ResourceName, "MSFT_DSCMetaConfiguration",
StringComparison.OrdinalIgnoreCase) == 0)
string.Equals(keyword.ResourceName, "MSFT_DSCMetaConfiguration",
StringComparison.OrdinalIgnoreCase))
{
if (keyword.Properties["RefreshFrequencyMins"] != null)
{

View file

@ -662,7 +662,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
{
if (x.controlBody.GetType() != controlReference.controlType)
continue;
if (string.Compare(controlReference.name, x.name, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(controlReference.name, x.name, StringComparison.OrdinalIgnoreCase))
return x.controlBody;
}

View file

@ -97,7 +97,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
string firstString = PSObject.AsPSObject(first).ToString();
string secondString = PSObject.AsPSObject(second).ToString();
return string.Compare(firstString, secondString, StringComparison.CurrentCultureIgnoreCase) == 0;
return string.Equals(firstString, secondString, StringComparison.CurrentCultureIgnoreCase);
}
/// <summary>

View file

@ -154,7 +154,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
#region Helper Methods
private static bool IsClass(string x, string y)
{
return string.Compare(x, y, StringComparison.OrdinalIgnoreCase) == 0;
return string.Equals(x, y, StringComparison.OrdinalIgnoreCase);
}
#if _UNUSED

View file

@ -96,7 +96,7 @@ namespace System.Management.Automation
EngineParser.SetPreviousFirstLastToken(Context);
}
if (errors.Any())
if (errors.Length > 0)
{
if (errors[0].IncompleteInput)
{

View file

@ -854,10 +854,10 @@ namespace System.Management.Automation
CommandAndName nextCommandAndName = cmdlets[lookAhead];
if (string.Compare(
if (string.Equals(
commandAndName.CommandName.ShortName,
nextCommandAndName.CommandName.ShortName,
StringComparison.OrdinalIgnoreCase) == 0)
StringComparison.OrdinalIgnoreCase))
{
AddCommandResult(commandAndName, true, completingAtStartOfLine, quote, results);
previousMatched = true;
@ -998,7 +998,7 @@ namespace System.Management.Automation
result.AddRange(s1);
for (int i = 0, j = 0; i < s2.Count; ++i)
{
if (j < s1.Count && string.Compare(s2[i].Path, s1[j].Path, StringComparison.CurrentCultureIgnoreCase) == 0)
if (j < s1.Count && string.Equals(s2[i].Path, s1[j].Path, StringComparison.CurrentCultureIgnoreCase))
{
++j;
continue;

View file

@ -1633,7 +1633,7 @@ namespace System.Management.Automation
IEnumerable<DynamicKeyword> keywords = configureAst.DefinedKeywords.Where(
k => // Node is special case, legal in both Resource and Meta configuration
string.Compare(k.Keyword, @"Node", StringComparison.OrdinalIgnoreCase) == 0 ||
string.Equals(k.Keyword, @"Node", StringComparison.OrdinalIgnoreCase) ||
(
// Check compatibility between Resource and Configuration Type
k.IsCompatibleWithConfigurationType(configureAst.ConfigurationType) &&
@ -1954,7 +1954,7 @@ namespace System.Management.Automation
// If the last token was just a '.', we tried to complete members. That may
// have failed because it wasn't really an attempt to complete a member, in
// which case we should try to complete as an argument.
if (result.Any())
if (result.Count > 0)
{
if (!isWildcard && memberOperator != TokenKind.Unknown)
{
@ -1969,7 +1969,7 @@ namespace System.Management.Automation
if (lastAst.Parent is HashtableAst)
{
result = CompletionCompleters.CompleteHashtableKey(completionContext, (HashtableAst)lastAst.Parent);
if (result != null && result.Any())
if (result != null && result.Count > 0)
{
return result;
}
@ -1992,7 +1992,7 @@ namespace System.Management.Automation
else if (tokenAtCursorText.IndexOfAny(Utils.Separators.Directory) == 0)
{
var command = lastAst.Parent as CommandBaseAst;
if (command != null && command.Redirections.Any())
if (command != null && command.Redirections.Count > 0)
{
var fileRedirection = command.Redirections[0] as FileRedirectionAst;
if (fileRedirection != null &&

View file

@ -120,7 +120,7 @@ namespace System.Management.Automation
foreach (var defn in findFunctionsVisitor.FunctionDefinitions)
{
if (commandNamePattern.IsMatch(defn.Name)
&& !commandResults.Where(cr => cr.CompletionText.Equals(defn.Name, StringComparison.OrdinalIgnoreCase)).Any())
&& !commandResults.Any(cr => cr.CompletionText.Equals(defn.Name, StringComparison.OrdinalIgnoreCase)))
{
// Results found in the current script are prepended to show up at the top of the list.
commandResults.Insert(0, GetCommandNameCompletionResult(defn.Name, defn, addAmpersandIfNecessary, quote));
@ -1603,7 +1603,7 @@ namespace System.Management.Automation
if (parameterSetData.ParameterSetFlag == defaultParameterSetFlag)
{
ProcessParameter(commandName, commandAst, context, result, param, boundArguments);
isProcessedAsPositional = result.Any();
isProcessedAsPositional = result.Count > 0;
break;
}
else
@ -2458,7 +2458,7 @@ namespace System.Management.Automation
{
}
if (customResults == null || !customResults.Any())
if (customResults == null || customResults.Count == 0)
{
return false;
}
@ -5409,7 +5409,7 @@ namespace System.Management.Automation
var memberInfo = member as MemberInfo;
if (memberInfo != null)
return memberInfo.GetCustomAttributes(typeof(HiddenAttribute), false).Any();
return memberInfo.GetCustomAttributes(typeof(HiddenAttribute), false).Length > 0;
var propertyMemberAst = member as PropertyMemberAst;
if (propertyMemberAst != null)

View file

@ -375,7 +375,7 @@ namespace System.Management.Automation
{
IEnumerable<PSSnapInInfo> loadedPSSnapIns = null;
loadedPSSnapIns = context.InitialSessionState.GetPSSnapIn(requiresPSSnapIn.Name);
if (loadedPSSnapIns == null || loadedPSSnapIns.Count() == 0)
if (loadedPSSnapIns == null || !loadedPSSnapIns.Any())
{
if (requiresMissingPSSnapIns == null)
{

View file

@ -649,7 +649,7 @@ namespace System.Management.Automation
// to an ICollection<T> is via reflected calls to Add(T),
// but the advantage over plain IList is that we can typecast the elements.
Type interfaceICollection =
interfaces.FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollection<>));
Array.Find(interfaces, i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollection<>));
if (interfaceICollection != null)
{
// We only deal with the first type for which ICollection<T> is implemented

View file

@ -2143,7 +2143,7 @@ namespace System.Management.Automation
// This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling
// against CoreCLR. So we need to add a null check until this is fixed in CLR.
var paramArrayAttrs = lastParameter.GetCustomAttributes(typeof(ParamArrayAttribute), false);
if (paramArrayAttrs != null && paramArrayAttrs.Any())
if (paramArrayAttrs != null && paramArrayAttrs.Length > 0)
{
this.hasVarArgs = true;
this.parameters[parametersLength - 1].isParamArray = true;
@ -4473,7 +4473,7 @@ namespace System.Management.Automation
// This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling
// against CoreCLR. So we need to add a null check until this is fixed in CLR.
var paramArrayAttrs = parameter.GetCustomAttributes(typeof(ParamArrayAttribute), false);
if (paramArrayAttrs != null && paramArrayAttrs.Any())
if (paramArrayAttrs != null && paramArrayAttrs.Length > 0)
builder.Append("Params ");
}

View file

@ -131,7 +131,7 @@ namespace System.Management.Automation
Text = "NOT";
break;
default:
Debug.Assert(false, "Invalid token kind passed in.");
Debug.Fail("Invalid token kind passed in.");
break;
}
}

View file

@ -716,7 +716,7 @@ namespace Microsoft.PowerShell.Commands
}
else
{
if (_modulePatterns.Count > 0 || _moduleSpecifications.Any())
if (_modulePatterns.Count > 0 || _moduleSpecifications.Length > 0)
{
// Its not a match if we are filtering on a PSSnapin/Module name but the cmdlet doesn't have one.
break;
@ -1491,10 +1491,10 @@ namespace Microsoft.PowerShell.Commands
foreach (CommandInfo commandInfo in _accumulatedResults)
{
if ((command.CommandType == commandInfo.CommandType &&
(string.Compare(command.Name, commandInfo.Name, StringComparison.OrdinalIgnoreCase) == 0 ||
(string.Equals(command.Name, commandInfo.Name, StringComparison.OrdinalIgnoreCase) ||
// If the command has been imported with a prefix, then just checking the names for duplication will not be enough.
// Hence, an additional check is done with the prefix information
string.Compare(ModuleCmdletBase.RemovePrefixFromCommandName(commandInfo.Name, commandInfo.Prefix), command.Name, StringComparison.OrdinalIgnoreCase) == 0)
string.Equals(ModuleCmdletBase.RemovePrefixFromCommandName(commandInfo.Name, commandInfo.Prefix), command.Name, StringComparison.OrdinalIgnoreCase))
) && commandInfo.Module != null && commandHasModule &&
( // We do reference equal comparison if both command are imported. If either one is not imported, we compare the module path
(commandInfo.IsImported && command.IsImported && commandInfo.Module.Equals(command.Module)) ||
@ -1601,7 +1601,7 @@ namespace Microsoft.PowerShell.Commands
bool hasParameterSet = false;
IList<string> validValues = new List<string>();
var validateSetAttribute = parameter.Attributes.Where(x => (x is ValidateSetAttribute)).Cast<ValidateSetAttribute>().LastOrDefault();
var validateSetAttribute = parameter.Attributes.OfType<ValidateSetAttribute>().LastOrDefault();
if (validateSetAttribute != null)
{
hasParameterSet = true;
@ -1631,7 +1631,7 @@ namespace Microsoft.PowerShell.Commands
returnParameterType.Properties.Add(new PSNoteProperty("EnumValues", enumValues));
bool hasFlagAttribute = (isArray) ?
((parameterType.GetCustomAttributes(typeof(FlagsAttribute), true)).Count() > 0) : false;
((parameterType.GetCustomAttributes(typeof(FlagsAttribute), true)).Length > 0) : false;
returnParameterType.Properties.Add(new PSNoteProperty("HasFlagAttribute", hasFlagAttribute));
// Recurse into array elements.

View file

@ -1973,7 +1973,7 @@ namespace System.Management.Automation
// See if the [Flag] attribute is set on this type...
// MemberInfo.GetCustomAttributes returns IEnumerable<Attribute> in CoreCLR.
bool hasFlagsAttribute = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any();
bool hasFlagsAttribute = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0;
returnValue = new EnumHashEntry(Enum.GetNames(enumType), values, allValues, hasNegativeValue, hasFlagsAttribute);
s_enumTable.Add(enumType, returnValue);
@ -2212,7 +2212,7 @@ namespace System.Management.Automation
}
else
{
if (string.Compare(sourceValueEntry, name, ignoreCaseOpt) != 0)
if (!string.Equals(sourceValueEntry, name, ignoreCaseOpt))
continue;
}
@ -5522,7 +5522,7 @@ namespace System.Management.Automation
// GetCustomAttributes returns IEnumerable<Attribute> in CoreCLR
var typeConverters = type.GetCustomAttributes(typeof(TypeConverterAttribute), false);
if (typeConverters.Any())
if (typeConverters.Length > 0)
{
return true;
}

View file

@ -965,7 +965,7 @@ namespace Microsoft.PowerShell.Commands
ValidateUriParameterValue(new Uri(_helpInfoUri), "HelpInfoUri");
}
if (CompatiblePSEditions != null && (CompatiblePSEditions.Distinct(StringComparer.OrdinalIgnoreCase).Count() != CompatiblePSEditions.Count()))
if (CompatiblePSEditions != null && (CompatiblePSEditions.Distinct(StringComparer.OrdinalIgnoreCase).Count() != CompatiblePSEditions.Length))
{
string message = StringUtil.Format(Modules.DuplicateEntriesInCompatiblePSEditions, string.Join(",", CompatiblePSEditions));
var ioe = new InvalidOperationException(message);

View file

@ -82,7 +82,7 @@ namespace System.Management.Automation
moduleInfo.DeclaredVariableExports = RehydrateHashtableKeys(deserializedModuleInfo, "ExportedVariables");
var compatiblePSEditions = DeserializingTypeConverter.GetPropertyValue<string[]>(deserializedModuleInfo, "CompatiblePSEditions", rehydrationFlags);
if (compatiblePSEditions != null && compatiblePSEditions.Any())
if (compatiblePSEditions != null && compatiblePSEditions.Length > 0)
{
foreach (var edition in compatiblePSEditions)
{
@ -92,7 +92,7 @@ namespace System.Management.Automation
// PowerShellGet related properties
var tags = DeserializingTypeConverter.GetPropertyValue<string[]>(deserializedModuleInfo, "Tags", rehydrationFlags);
if (tags != null && tags.Any())
if (tags != null && tags.Length > 0)
{
foreach (var tag in tags)
{

View file

@ -3520,7 +3520,7 @@ namespace System.Management.Automation
out targetProvider,
out targetProviderInstance);
if (string.Compare(targetProvider.Name, "filesystem", StringComparison.OrdinalIgnoreCase) != 0)
if (!string.Equals(targetProvider.Name, "filesystem", StringComparison.OrdinalIgnoreCase))
{
throw PSTraceSource.NewNotSupportedException(SessionStateStrings.MustBeFileSystemPath);
}

View file

@ -170,7 +170,7 @@ namespace System.Management.Automation
return;
}
if (string.Compare(result.Name, drive.Name, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(result.Name, drive.Name, StringComparison.OrdinalIgnoreCase))
{
// Set the drive in the current scope.
@ -1294,7 +1294,7 @@ namespace System.Management.Automation
// Make sure the provider didn't try to pull a fast one on us
// and substitute a different drive.
if (string.Compare(result.Name, drive.Name, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(result.Name, drive.Name, StringComparison.OrdinalIgnoreCase))
{
driveRemovable = true;
}

View file

@ -733,7 +733,7 @@ namespace System.Management.Automation
providerSpecificPath,
currentWorkingPath);
if (string.Compare(providerSpecificPath, currentWorkingPath, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(providerSpecificPath, currentWorkingPath, StringComparison.OrdinalIgnoreCase))
{
// The path is the current working directory so
// return true
@ -765,7 +765,7 @@ namespace System.Management.Automation
lockedDirectory,
providerSpecificPath);
if (string.Compare(lockedDirectory, providerSpecificPath, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(lockedDirectory, providerSpecificPath, StringComparison.OrdinalIgnoreCase))
{
// The path is a parent of the current working
// directory

View file

@ -440,7 +440,7 @@ namespace System.Management.Automation
}
if (variable is LocalVariable
&& (variableToSet.Attributes.Any() || variableToSet.Options != variable.Options))
&& (variableToSet.Attributes.Count > 0 || variableToSet.Options != variable.Options))
{
SessionStateUnauthorizedAccessException e =
new SessionStateUnauthorizedAccessException(
@ -1952,7 +1952,7 @@ namespace System.Management.Automation
}
else
{
string itemToRemove = list.FirstOrDefault(item => item.Equals(alias, StringComparison.OrdinalIgnoreCase));
string itemToRemove = list.Find(item => item.Equals(alias, StringComparison.OrdinalIgnoreCase));
if (itemToRemove != null)
{
list.Remove(itemToRemove);

View file

@ -2328,7 +2328,7 @@ namespace System.Management.Automation.Runspaces
newTypeData.StringSerializationSource = this.StringSerializationSource;
break;
default:
Dbg.Assert(false, "Standard members should at most contain six kinds of elements");
Dbg.Fail("Standard members should at most contain six kinds of elements");
break;
}
}
@ -2948,7 +2948,7 @@ namespace System.Management.Automation.Runspaces
for (int i = 0; i < members.Count; i++)
{
PSMemberInfo member = members[i];
if (string.Compare(member.Name, noteName, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(member.Name, noteName, StringComparison.OrdinalIgnoreCase))
{
noteAsMemberInfo = member;
}
@ -2978,7 +2978,7 @@ namespace System.Management.Automation.Runspaces
}
else
{
note.noteValue = string.Compare(sourceValueAsString, "false", StringComparison.OrdinalIgnoreCase) != 0;
note.noteValue = !string.Equals(sourceValueAsString, "false", StringComparison.OrdinalIgnoreCase);
}
return true;
@ -3003,7 +3003,7 @@ namespace System.Management.Automation.Runspaces
for (int i = 0; i < members.Count; i++)
{
PSMemberInfo member = members[i];
if (string.Compare(member.Name, memberName, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(member.Name, memberName, StringComparison.OrdinalIgnoreCase))
{
AddError(errors, typeName, TypesXmlStrings.MemberShouldNotBePresent, member.Name);
return false;
@ -3019,7 +3019,7 @@ namespace System.Management.Automation.Runspaces
for (int i = 0; i < members.Count; i++)
{
PSMemberInfo m = members[i];
if (string.Compare(m.Name, noteName, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(m.Name, noteName, StringComparison.OrdinalIgnoreCase))
{
member = m;
}

View file

@ -1402,10 +1402,10 @@ namespace System.Management.Automation
_commandBreakpoints.Values.Where(bp => bp.Enabled && bp.Trigger(invocationInfo)).ToList<Breakpoint>();
bool checkLineBp = true;
if (breakpoints.Any())
if (breakpoints.Count > 0)
{
breakpoints = TriggerBreakpoints(breakpoints);
if (breakpoints.Any())
if (breakpoints.Count > 0)
{
var breakInvocationInfo =
functionContext != null
@ -1422,7 +1422,7 @@ namespace System.Management.Automation
internal void CheckVariableRead(string variableName)
{
var breakpointsToTrigger = GetVariableBreakpointsToTrigger(variableName, read: true);
if (breakpointsToTrigger != null && breakpointsToTrigger.Any())
if (breakpointsToTrigger != null && breakpointsToTrigger.Count > 0)
{
TriggerVariableBreakpoints(breakpointsToTrigger);
}
@ -1431,7 +1431,7 @@ namespace System.Management.Automation
internal void CheckVariableWrite(string variableName)
{
var breakpointsToTrigger = GetVariableBreakpointsToTrigger(variableName, read: false);
if (breakpointsToTrigger != null && breakpointsToTrigger.Any())
if (breakpointsToTrigger != null && breakpointsToTrigger.Count > 0)
{
TriggerVariableBreakpoints(breakpointsToTrigger);
}
@ -1580,7 +1580,7 @@ namespace System.Management.Automation
select breakpoint).ToList<Breakpoint>();
breakpoints = TriggerBreakpoints(breakpoints);
if (breakpoints.Any())
if (breakpoints.Count > 0)
{
StopOnSequencePoint(functionContext, breakpoints);
}
@ -1949,7 +1949,7 @@ namespace System.Management.Automation
throw new TerminateException();
default:
Debug.Assert(false, "Received an unknown action: " + action);
Debug.Fail("Received an unknown action: " + action);
break;
}
}
@ -2020,7 +2020,7 @@ namespace System.Management.Automation
private void SetPendingBreakpoints(FunctionContext functionContext)
{
if (!_pendingBreakpoints.Any())
if (_pendingBreakpoints.Count == 0)
return;
var newPendingBreakpoints = new Dictionary<int, LineBreakpoint>();
@ -3628,7 +3628,7 @@ namespace System.Management.Automation
if ((runspaceInfo.Runspace.Debugger != null) &&
runspaceInfo.Runspace.Debugger.Equals(this))
{
Debug.Assert(false, "Nested debugger cannot be the root debugger.");
Debug.Fail("Nested debugger cannot be the root debugger.");
return;
}
@ -5615,7 +5615,7 @@ namespace System.Management.Automation
break;
}
if (scope.DottedScopes != null && scope.DottedScopes.Where(s => s == FunctionContext._localsTuple).Any())
if (scope.DottedScopes != null && scope.DottedScopes.Any(s => s == FunctionContext._localsTuple))
{
var dottedScopes = scope.DottedScopes.ToArray();

View file

@ -249,7 +249,7 @@ namespace System.Management.Automation.Runspaces
}
default:
Debug.Assert(false);
Debug.Fail("");
break;
}
}

View file

@ -1288,7 +1288,7 @@ namespace System.Management.Automation.Host
#endregion SplitLabel
// ? is not localizable
if (string.Compare(hotkeysAndPlainLabels[0, i], "?", StringComparison.Ordinal) == 0)
if (string.Equals(hotkeysAndPlainLabels[0, i], "?", StringComparison.Ordinal))
{
Exception e = PSTraceSource.NewArgumentException(
string.Format(Globalization.CultureInfo.InvariantCulture, "choices[{0}].Label", i),
@ -1320,7 +1320,7 @@ namespace System.Management.Automation.Host
for (int i = 0; i < choices.Count; ++i)
{
// pick the one that matches either the hot key or the full label
if (string.Compare(response, hotkeysAndPlainLabels[1, i], StringComparison.CurrentCultureIgnoreCase) == 0)
if (string.Equals(response, hotkeysAndPlainLabels[1, i], StringComparison.CurrentCultureIgnoreCase))
{
result = i;
break;
@ -1335,7 +1335,7 @@ namespace System.Management.Automation.Host
// Ignore labels with empty hotkeys
if (hotkeysAndPlainLabels[0, i].Length > 0)
{
if (string.Compare(response, hotkeysAndPlainLabels[0, i], StringComparison.CurrentCultureIgnoreCase) == 0)
if (string.Equals(response, hotkeysAndPlainLabels[0, i], StringComparison.CurrentCultureIgnoreCase))
{
result = i;
break;

View file

@ -167,7 +167,7 @@ namespace System.Management.Automation.Interpreter
internal int GotoHandler(InterpretedFrame frame, object exception, out ExceptionHandler handler)
{
Debug.Assert(_handlers != null, "we should have at least one handler if the method gets called");
handler = _handlers.FirstOrDefault(t => t.Matches(exception.GetType()));
handler = Array.Find(_handlers, t => t.Matches(exception.GetType()));
if (handler == null) { return 0; }
return frame.Goto(handler.LabelIndex, exception, gotoExceptionHandler: true);

View file

@ -905,7 +905,7 @@ namespace System.Management.Automation.Interpreter
{
get
{
Debug.Assert(false, "Unreachable");
Debug.Fail("Unreachable");
return new InvalidOperationException("Code supposed to be unreachable");
}
}

View file

@ -463,7 +463,7 @@ namespace System.Management.Automation
if (variablesToDefine != null)
{
// Extract the special variables "this", "input" and "_"
PSVariable located = variablesToDefine.FirstOrDefault(
PSVariable located = variablesToDefine.Find(
v => string.Equals(v.Name, "this", StringComparison.OrdinalIgnoreCase));
if (located != null)
{
@ -471,7 +471,7 @@ namespace System.Management.Automation
variablesToDefine.Remove(located);
}
located = variablesToDefine.FirstOrDefault(
located = variablesToDefine.Find(
v => string.Equals(v.Name, "_", StringComparison.Ordinal));
if (located != null)
{
@ -479,7 +479,7 @@ namespace System.Management.Automation
variablesToDefine.Remove(located);
}
located = variablesToDefine.FirstOrDefault(
located = variablesToDefine.Find(
v => string.Equals(v.Name, "input", StringComparison.OrdinalIgnoreCase));
if (located != null)
{

View file

@ -374,7 +374,7 @@ namespace System.Management.Automation.Language
var searcher = new AstSearcher(predicate, stopOnFirst: true, searchNestedScriptBlocks: searchNestedScriptBlocks);
ast.InternalVisit(searcher);
return searcher.Results.FirstOrDefault() != null;
return searcher.Results.Any();
}
internal static bool IsUsingDollarInput(Ast ast)

View file

@ -2591,7 +2591,7 @@ namespace System.Management.Automation.Language
// If Parent of rootForDefiningTypesAndUsings is not null, then we already defined all types, when Visit a parent ScriptBlock
if (rootForDefiningTypesAndUsings.Parent == null)
{
if (rootForDefiningTypesAndUsings.UsingStatements.Any())
if (rootForDefiningTypesAndUsings.UsingStatements.Count > 0)
{
bool allUsingsAreNamespaces = rootForDefiningTypesAndUsings.UsingStatements.All(us => us.UsingStatementKind == UsingStatementKind.Namespace);
GenerateLoadUsings(rootForDefiningTypesAndUsings.UsingStatements, allUsingsAreNamespaces, exprs);

View file

@ -110,7 +110,7 @@ namespace System.Management.Automation.Language
// This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling
// against CoreCLR. So we need to add a null check until this is fixed in CLR.
var paramArrayAttrs = parameterInfo[argIndex].GetCustomAttributes(typeof(ParamArrayAttribute), true);
if (paramArrayAttrs != null && paramArrayAttrs.Any() && expandParamsOnBest)
if (paramArrayAttrs != null && paramArrayAttrs.Length > 0 && expandParamsOnBest)
{
var elementType = parameterInfo[argIndex].ParameterType.GetElementType();
var paramsArray = Array.CreateInstance(elementType, positionalArgCount - argIndex);
@ -323,7 +323,7 @@ namespace System.Management.Automation.Language
// Default base class is System.Object and it has a default ctor.
_baseClassHasDefaultCtor = true;
if (typeDefinitionAst.BaseTypes.Any())
if (typeDefinitionAst.BaseTypes.Count > 0)
{
// base class
var baseTypeAsts = typeDefinitionAst.BaseTypes;
@ -550,7 +550,7 @@ namespace System.Management.Automation.Language
if (needDefaultCtor)
{
needDefaultCtor = !instanceCtors.Any();
needDefaultCtor = instanceCtors.Count == 0;
}
//// Now we can decide to create explicit default ctors or report error.
@ -571,7 +571,7 @@ namespace System.Management.Automation.Language
}
else
{
if (!instanceCtors.Any())
if (instanceCtors.Count == 0)
{
_parser.ReportError(_typeDefinitionAst.Extent,
nameof(ParserStrings.BaseClassNoDefaultCtor),
@ -838,7 +838,7 @@ namespace System.Management.Automation.Language
var parameters = functionMemberAst.Parameters;
if (parameters.Count > 0)
{
IScriptExtent errorExtent = Parser.ExtentOf(parameters.First(), parameters.Last());
IScriptExtent errorExtent = Parser.ExtentOf(parameters[0], parameters.Last());
_parser.ReportError(errorExtent,
nameof(ParserStrings.StaticConstructorCantHaveParameters),
ParserStrings.StaticConstructorCantHaveParameters);
@ -888,7 +888,7 @@ namespace System.Management.Automation.Language
}
var ilGenerator = method.GetILGenerator();
DefineMethodBody(functionMemberAst, ilGenerator, GetMetaDataName(method.Name, parameterTypes.Count()), functionMemberAst.IsStatic, parameterTypes, returnType,
DefineMethodBody(functionMemberAst, ilGenerator, GetMetaDataName(method.Name, parameterTypes.Length), functionMemberAst.IsStatic, parameterTypes, returnType,
(i, n) => method.DefineParameter(i, ParameterAttributes.None, n));
}
@ -917,7 +917,7 @@ namespace System.Management.Automation.Language
ilGenerator.Emit(OpCodes.Stfld, _sessionStateField);
}
DefineMethodBody(ipmp, ilGenerator, GetMetaDataName(ctor.Name, parameterTypes.Count()), isStatic, parameterTypes, typeof(void),
DefineMethodBody(ipmp, ilGenerator, GetMetaDataName(ctor.Name, parameterTypes.Length), isStatic, parameterTypes, typeof(void),
(i, n) => ctor.DefineParameter(i, ParameterAttributes.None, n));
}

View file

@ -880,7 +880,7 @@ namespace System.Management.Automation.Language
UngetToken(rParen);
endExtent = Before(rParen);
ReportIncompleteInput(After(parameters != null && parameters.Any() ? parameters.Last().Extent : lparen.Extent),
ReportIncompleteInput(After(parameters != null && parameters.Count > 0 ? parameters.Last().Extent : lparen.Extent),
nameof(ParserStrings.MissingEndParenthesisInFunctionParameterList),
ParserStrings.MissingEndParenthesisInFunctionParameterList);
}
@ -3936,7 +3936,7 @@ namespace System.Management.Automation.Language
else if (keywordData.BodyMode == DynamicKeywordBodyMode.Hashtable)
{
// Resource property value could be set to nested DSC resources except Script resource
bool isScriptResource = string.Compare(functionName.Text, @"Script", StringComparison.OrdinalIgnoreCase) == 0;
bool isScriptResource = string.Equals(functionName.Text, @"Script", StringComparison.OrdinalIgnoreCase);
try
{
if (isScriptResource)
@ -5369,7 +5369,7 @@ namespace System.Management.Automation.Language
// ErrorRecovery: assume a body follows, so just keep parsing.
UngetToken(rParen);
endErrorStatement = parameters.Any() ? parameters.Last().Extent : lParen.Extent;
endErrorStatement = parameters.Count > 0 ? parameters.Last().Extent : lParen.Extent;
ReportIncompleteInput(After(endErrorStatement),
nameof(ParserStrings.MissingEndParenthesisInFunctionParameterList),
ParserStrings.MissingEndParenthesisInFunctionParameterList);
@ -6277,7 +6277,7 @@ namespace System.Management.Automation.Language
nameof(ParserStrings.MissingExpression),
ParserStrings.MissingExpression,
",");
return new ErrorExpressionAst(ExtentOf(commandArgs.First(), commaToken), commandArgs);
return new ErrorExpressionAst(ExtentOf(commandArgs[0], commaToken), commandArgs);
case TokenKind.SplattedVariable:
case TokenKind.Variable:
@ -7577,7 +7577,7 @@ namespace System.Management.Automation.Language
List<Token> newNestedTokens = _savingTokens ? new List<Token>() : null;
foreach (var token in expandableStringToken.NestedTokens)
{
Diagnostics.Assert(!token.HasError || ErrorList.Any(), "No nested tokens should have unreported errors.");
Diagnostics.Assert(!token.HasError || ErrorList.Count > 0, "No nested tokens should have unreported errors.");
ExpressionAst exprAst;
var varToken = token as VariableToken;
@ -7807,7 +7807,7 @@ namespace System.Management.Automation.Language
UngetToken(rParen);
if (!reportedError)
{
ReportIncompleteInput(arguments.Any() ? After(arguments.Last()) : After(lParen),
ReportIncompleteInput(arguments.Count > 0 ? After(arguments.Last()) : After(lParen),
nameof(ParserStrings.MissingEndParenthesisInMethodCall),
ParserStrings.MissingEndParenthesisInMethodCall);
}
@ -7893,7 +7893,7 @@ namespace System.Management.Automation.Language
{
AssertErrorIdCorrespondsToMsgString(errorId, errorMsg);
if (args != null && args.Any())
if (args != null && args.Length > 0)
{
errorMsg = string.Format(CultureInfo.CurrentCulture, errorMsg, args);
}

View file

@ -1811,7 +1811,7 @@ namespace System.Management.Automation.Language
var parser = new Parser();
var rlc = new RestrictedLanguageChecker(parser, allowedCommands, null, false);
dataStatementAst.Body.InternalVisit(rlc);
if (parser.ErrorList.Any())
if (parser.ErrorList.Count > 0)
{
throw new ParseException(parser.ErrorList.ToArray());
}

View file

@ -1231,7 +1231,7 @@ namespace System.Management.Automation
}
var memberNameAndTypes = GetMemberNameAndTypeFromProperties(prevType, IsInPropertyArgument);
if (!memberNameAndTypes.Any())
if (memberNameAndTypes.Count == 0)
{
continue;
}
@ -1328,7 +1328,7 @@ namespace System.Management.Automation
switch (propertyNameOrPattern)
{
case string propertyName:
if (string.Compare(name, propertyName, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(name, propertyName, StringComparison.OrdinalIgnoreCase))
{
return includeMatchedProperties;
}

View file

@ -103,7 +103,7 @@ namespace System.Management.Automation.Language
visitor.VisitParameters(ast.Parameters);
}
localsAllocated = visitor._variables.Where(details => details.Value.LocalTupleIndex != VariableAnalysis.Unanalyzed).Count();
localsAllocated = visitor._variables.Count(details => details.Value.LocalTupleIndex != VariableAnalysis.Unanalyzed);
return visitor._variables;
}
@ -1416,7 +1416,7 @@ namespace System.Management.Automation.Language
if (label != null)
{
label.Accept(this);
if (_loopTargets.Any())
if (_loopTargets.Count > 0)
{
var labelStrAst = label as StringConstantExpressionAst;
if (labelStrAst != null)
@ -1600,7 +1600,7 @@ namespace System.Management.Automation.Language
// break or continue, so add the appropriate edges to our graph. These edges occur after visiting
// the command elements because command arguments could create new blocks, and we won't have executed
// the command yet.
if (invokesCommand && _loopTargets.Any())
if (invokesCommand && _loopTargets.Count > 0)
{
foreach (var loopTarget in _loopTargets)
{

View file

@ -223,7 +223,7 @@ namespace System.Management.Automation.Language
if (elements == null || elements.Count == 0) { return null; }
var result = new T[elements.Count];
for (int i = 0; i < result.Count(); i++)
for (int i = 0; i < result.Length; i++)
{
result[i] = (T)elements[i].Copy();
}
@ -1138,7 +1138,7 @@ namespace System.Management.Automation.Language
// It's ok to report an error from a different part of AST in this case.
var root = GetRootScriptBlockAst();
root.PerformPostParseChecks(parser);
if (parser.ErrorList.Any())
if (parser.ErrorList.Count > 0)
{
throw new ParseException(parser.ErrorList.ToArray());
}
@ -1573,7 +1573,7 @@ namespace System.Management.Automation.Language
return null;
}
if (EndBlock.Traps != null && EndBlock.Traps.Any())
if (EndBlock.Traps != null && EndBlock.Traps.Count > 0)
{
errorId = "CantConvertScriptBlockWithTrap";
errorMsg = AutomationExceptions.CantConvertScriptBlockWithTrap;
@ -1781,7 +1781,7 @@ namespace System.Management.Automation.Language
SetParents(statements);
var traps = statementBlock.Traps;
if (traps != null && traps.Any())
if (traps != null && traps.Count > 0)
{
this.Traps = traps;
for (int index = 0; index < traps.Count; index++)
@ -5609,7 +5609,7 @@ namespace System.Management.Automation.Language
}
CommandExpressionAst expr = PipelineElements[0] as CommandExpressionAst;
if (expr != null && !expr.Redirections.Any())
if (expr != null && expr.Redirections.Count == 0)
{
return expr.Expression;
}
@ -6852,7 +6852,7 @@ namespace System.Management.Automation.Language
public DynamicKeywordStatementAst(IScriptExtent extent,
IEnumerable<CommandElementAst> commandElements) : base(extent)
{
if (commandElements == null || commandElements.Count() <= 0)
if (commandElements == null || !commandElements.Any())
{
throw PSTraceSource.NewArgumentException(nameof(commandElements));
}
@ -8282,7 +8282,7 @@ namespace System.Management.Automation.Language
if (function.IsConstructor)
{
// TODO: add check for default values, once default values for parameters supported
if (!function.Parameters.Any())
if (function.Parameters.Count == 0)
{
return true;
}
@ -9760,7 +9760,7 @@ namespace System.Management.Automation.Language
public ArrayLiteralAst(IScriptExtent extent, IList<ExpressionAst> elements)
: base(extent)
{
if (elements == null || !elements.Any())
if (elements == null || elements.Count == 0)
{
throw PSTraceSource.NewArgumentException(nameof(elements));
}

View file

@ -391,7 +391,7 @@ namespace System.Management.Automation.Language
internal static IEnumerable<DynamicKeyword> GetAllowedKeywords(this DynamicKeyword keyword, IEnumerable<DynamicKeyword> allowedKeywords)
{
string keywordName = keyword.Keyword;
if (string.Compare(keywordName, @"Node", StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(keywordName, @"Node", StringComparison.OrdinalIgnoreCase))
{
List<string> excludeKeywords;
if (s_excludeKeywords.TryGetValue(keywordName, out excludeKeywords))

View file

@ -562,7 +562,7 @@ namespace Microsoft.PowerShell.Commands
break;
default:
Debug.Assert(false, "Unknown parameter set.");
Debug.Fail("Unknown parameter set.");
processAppDomainInfo = new ReadOnlyCollection<PSHostProcessInfo>(new Collection<PSHostProcessInfo>());
break;
}

View file

@ -467,7 +467,7 @@ namespace Microsoft.PowerShell.Commands
// Find specified session.
bool haveMatch = false;
if (!string.IsNullOrEmpty(name) &&
string.Compare(name, ((RemoteRunspace)runspace).RunspacePool.RemoteRunspacePoolInternal.Name, StringComparison.OrdinalIgnoreCase) == 0)
string.Equals(name, ((RemoteRunspace)runspace).RunspacePool.RemoteRunspacePoolInternal.Name, StringComparison.OrdinalIgnoreCase))
{
// Selected by friendly name.
haveMatch = true;

View file

@ -247,7 +247,7 @@ namespace Microsoft.PowerShell.Commands
{
lock (_jobTrackingLock)
{
return _jobsToWaitFor.FirstOrDefault(j => j.JobStateInfo.State == JobState.Blocked);
return _jobsToWaitFor.Find(j => j.JobStateInfo.State == JobState.Blocked);
}
}

View file

@ -268,7 +268,7 @@ namespace System.Management.Automation.Remoting
if (ex != null)
{
Dbg.Assert(false, "Unexpected error in RemoteSessionHyperVSocketServer.");
Dbg.Fail("Unexpected error in RemoteSessionHyperVSocketServer.");
// Unexpected error.
string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
@ -575,7 +575,7 @@ namespace System.Management.Automation.Remoting
//
// Credential is invalid.
//
if (string.Compare(responseString, "FAIL", StringComparison.Ordinal) == 0)
if (string.Equals(responseString, "FAIL", StringComparison.Ordinal))
{
HyperVSocket.Send(response);
@ -586,7 +586,7 @@ namespace System.Management.Automation.Remoting
//
// If PowerShell Direct in VM supports configuration, send configuration name.
//
if (string.Compare(responseString, "CONF", StringComparison.Ordinal) == 0)
if (string.Equals(responseString, "CONF", StringComparison.Ordinal))
{
if (emptyConfiguration)
{

View file

@ -1683,7 +1683,7 @@ namespace System.Management.Automation.Language
// This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling
// against CoreCLR. So we need to add a null check until this is fixed in CLR.
var paramArrayAttrs = parameterInfo[argIndex].GetCustomAttributes(typeof(ParamArrayAttribute), true);
if (paramArrayAttrs != null && paramArrayAttrs.Any() && expandParamsOnBest)
if (paramArrayAttrs != null && paramArrayAttrs.Length > 0 && expandParamsOnBest)
{
var elementType = parameterInfo[argIndex].ParameterType.GetElementType();
var paramsArray = new List<Expression>();
@ -1714,7 +1714,7 @@ namespace System.Management.Automation.Language
}
Expression result = Expression.New(constructorInfo, ctorArgs);
if (CallInfo.ArgumentNames.Any())
if (CallInfo.ArgumentNames.Count > 0)
{
var tmp = Expression.Parameter(result.Type);
var blockExprs = new List<Expression>();
@ -2036,7 +2036,7 @@ namespace System.Management.Automation.Language
}
// If there are any fields, the type is mutable.
if (type.GetFields(BindingFlags.Public | BindingFlags.Instance).Any())
if (type.GetFields(BindingFlags.Public | BindingFlags.Instance).Length > 0)
{
return true;
}
@ -5102,7 +5102,7 @@ namespace System.Management.Automation.Language
var binderList = s_binderCacheIgnoringCase.GetOrAdd(memberName, _ => new List<PSGetMemberBinder>());
lock (binderList)
{
if (binderList.Any())
if (binderList.Count > 0)
{
result._hasInstanceMember = binderList[0]._hasInstanceMember;
result._hasTypeTableMember = binderList[0]._hasTypeTableMember;
@ -7084,7 +7084,7 @@ namespace System.Management.Automation.Language
// This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling
// against CoreCLR. So we need to add a null check until this is fixed in CLR.
var paramArrayAttrs = parameters[i].GetCustomAttributes(typeof(ParamArrayAttribute), false);
if (paramArrayAttrs != null && paramArrayAttrs.Any())
if (paramArrayAttrs != null && paramArrayAttrs.Length > 0)
{
Diagnostics.Assert(i == parameters.Length - 1, "vararg parameter is not the last");
var paramElementType = parameterType.GetElementType();
@ -7204,9 +7204,9 @@ namespace System.Management.Automation.Language
}
}
if (temps.Any())
if (temps.Count > 0)
{
if (call.Type != typeof(void) && copyOutTemps.Any())
if (call.Type != typeof(void) && copyOutTemps.Count > 0)
{
var retValue = Expression.Variable(call.Type);
temps.Add(retValue);

View file

@ -428,7 +428,7 @@ namespace System.Management.Automation
}
return _usesCmdletBinding
? (CmdletBindingAttribute)_attributes.FirstOrDefault(attr => attr is CmdletBindingAttribute)
? (CmdletBindingAttribute)Array.Find(_attributes, attr => attr is CmdletBindingAttribute)
: null;
}
}
@ -442,7 +442,7 @@ namespace System.Management.Automation
InitializeMetadata();
}
return (ObsoleteAttribute)_attributes.FirstOrDefault(attr => attr is ObsoleteAttribute);
return (ObsoleteAttribute)Array.Find(_attributes, attr => attr is ObsoleteAttribute);
}
}
@ -748,7 +748,7 @@ namespace System.Management.Automation
var ast = AstInternal;
var statements = ast.Body.EndBlock.Statements;
if (!statements.Any())
if (statements.Count == 0)
{
return errorHandler(AutomationExceptions.CantConvertEmptyPipeline);
}
@ -758,7 +758,7 @@ namespace System.Management.Automation
return errorHandler(AutomationExceptions.CanOnlyConvertOnePipeline);
}
if (ast.Body.EndBlock.Traps != null && ast.Body.EndBlock.Traps.Any())
if (ast.Body.EndBlock.Traps != null && ast.Body.EndBlock.Traps.Count > 0)
{
return errorHandler(AutomationExceptions.CantConvertScriptBlockWithTrap);
}
@ -904,7 +904,7 @@ namespace System.Management.Automation
AstVisitAction.Continue);
}
if (parser.ErrorList.Any())
if (parser.ErrorList.Count > 0)
{
throw new ParseException(parser.ErrorList.ToArray());
}

View file

@ -4019,7 +4019,7 @@ namespace System.Management.Automation
}
string name = ReadNameAttribute();
if (string.Compare(name, SerializationStrings.DictionaryKey, StringComparison.OrdinalIgnoreCase) != 0)
if (!string.Equals(name, SerializationStrings.DictionaryKey, StringComparison.OrdinalIgnoreCase))
{
throw NewXmlException(Serialization.InvalidDictionaryKeyName, null);
}
@ -4037,7 +4037,7 @@ namespace System.Management.Automation
}
name = ReadNameAttribute();
if (string.Compare(name, SerializationStrings.DictionaryValue, StringComparison.OrdinalIgnoreCase) != 0)
if (!string.Equals(name, SerializationStrings.DictionaryValue, StringComparison.OrdinalIgnoreCase))
{
throw NewXmlException(Serialization.InvalidDictionaryValueName, null);
}

View file

@ -696,7 +696,7 @@ namespace System.Management.Automation
for (int i = 0; i < doc.ChildNodes.Count; i++)
{
XmlNode node = doc.ChildNodes[i];
if (node.NodeType == XmlNodeType.Element && string.Compare(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase) == 0)
if (node.NodeType == XmlNodeType.Element && string.Equals(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase))
{
helpItemsNode = node;
break;
@ -719,7 +719,7 @@ namespace System.Management.Automation
for (int i = 0; i < helpItemsNode.ChildNodes.Count; i++)
{
XmlNode node = helpItemsNode.ChildNodes[i];
if (node.NodeType == XmlNodeType.Element && string.Compare(node.LocalName, "command", StringComparison.OrdinalIgnoreCase) == 0)
if (node.NodeType == XmlNodeType.Element && string.Equals(node.LocalName, "command", StringComparison.OrdinalIgnoreCase))
{
MamlCommandHelpInfo helpInfo = null;
@ -735,7 +735,7 @@ namespace System.Management.Automation
}
}
if (node.NodeType == XmlNodeType.Element && string.Compare(node.Name, "UserDefinedData", StringComparison.OrdinalIgnoreCase) == 0)
if (node.NodeType == XmlNodeType.Element && string.Equals(node.Name, "UserDefinedData", StringComparison.OrdinalIgnoreCase))
{
UserDefinedHelpData userDefinedHelpData = UserDefinedHelpData.Load(node);

View file

@ -317,7 +317,7 @@ namespace System.Management.Automation
for (int i = 0; i < doc.ChildNodes.Count; i++)
{
XmlNode node = doc.ChildNodes[i];
if (node.NodeType == XmlNodeType.Element && string.Compare(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase) == 0)
if (node.NodeType == XmlNodeType.Element && string.Equals(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase))
{
helpItemsNode = node;
break;
@ -343,7 +343,7 @@ namespace System.Management.Automation
string nodeLocalName = node.LocalName;
bool isDscResource = (string.Compare(nodeLocalName, "dscResource", StringComparison.OrdinalIgnoreCase) == 0);
bool isDscResource = (string.Equals(nodeLocalName, "dscResource", StringComparison.OrdinalIgnoreCase));
if (node.NodeType == XmlNodeType.Element && isDscResource)
{

View file

@ -214,9 +214,9 @@ namespace System.Management.Automation
if (xmlNode.Attributes["type"] != null)
{
if (string.Compare(xmlNode.Attributes["type"].Value, "field", StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(xmlNode.Attributes["type"].Value, "field", StringComparison.OrdinalIgnoreCase))
mshObject.TypeNames.Add("MamlPSClassHelpInfo#field");
else if (string.Compare(xmlNode.Attributes["type"].Value, "method", StringComparison.OrdinalIgnoreCase) == 0)
else if (string.Equals(xmlNode.Attributes["type"].Value, "method", StringComparison.OrdinalIgnoreCase))
mshObject.TypeNames.Add("MamlPSClassHelpInfo#method");
}

View file

@ -322,7 +322,7 @@ namespace System.Management.Automation
for (int i = 0; i < doc.ChildNodes.Count; i++)
{
XmlNode node = doc.ChildNodes[i];
if (node.NodeType == XmlNodeType.Element && string.Compare(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase) == 0)
if (node.NodeType == XmlNodeType.Element && string.Equals(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase))
{
helpItemsNode = node;
break;
@ -348,7 +348,7 @@ namespace System.Management.Automation
string nodeLocalName = node.LocalName;
bool isClass = (string.Compare(nodeLocalName, "class", StringComparison.OrdinalIgnoreCase) == 0);
bool isClass = (string.Equals(nodeLocalName, "class", StringComparison.OrdinalIgnoreCase));
if (node.NodeType == XmlNodeType.Element && isClass)
{

View file

@ -209,7 +209,7 @@ namespace System.Management.Automation
for (int i = 0; i < doc.ChildNodes.Count; i++)
{
XmlNode node = doc.ChildNodes[i];
if (node.NodeType == XmlNodeType.Element && string.Compare(node.Name, "helpItems", StringComparison.OrdinalIgnoreCase) == 0)
if (node.NodeType == XmlNodeType.Element && string.Equals(node.Name, "helpItems", StringComparison.OrdinalIgnoreCase))
{
helpItemsNode = node;
break;
@ -227,7 +227,7 @@ namespace System.Management.Automation
for (int i = 0; i < helpItemsNode.ChildNodes.Count; i++)
{
XmlNode node = helpItemsNode.ChildNodes[i];
if (node.NodeType == XmlNodeType.Element && string.Compare(node.Name, "providerHelp", StringComparison.OrdinalIgnoreCase) == 0)
if (node.NodeType == XmlNodeType.Element && string.Equals(node.Name, "providerHelp", StringComparison.OrdinalIgnoreCase))
{
HelpInfo helpInfo = ProviderHelpInfo.Load(node);

View file

@ -107,8 +107,8 @@ namespace System.Management.Automation.Help
foreach (CultureSpecificUpdatableHelp updatableHelpItem in UpdatableHelpItems)
{
if (string.Compare(updatableHelpItem.Culture.Name, culture.Name,
StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(updatableHelpItem.Culture.Name, culture.Name,
StringComparison.OrdinalIgnoreCase))
{
return true;
}
@ -152,8 +152,8 @@ namespace System.Management.Automation.Help
{
foreach (CultureSpecificUpdatableHelp updatableHelpItem in UpdatableHelpItems)
{
if (string.Compare(updatableHelpItem.Culture.Name, culture.Name,
StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(updatableHelpItem.Culture.Name, culture.Name,
StringComparison.OrdinalIgnoreCase))
{
return updatableHelpItem.Version;
}

View file

@ -167,7 +167,7 @@ namespace Microsoft.PowerShell.Commands
var entries = Directory.GetFileSystemEntries(exactPath, item);
if (entries.Length > 0)
{
exactPath = entries.First();
exactPath = entries[0];
}
else
{
@ -1417,10 +1417,10 @@ namespace Microsoft.PowerShell.Commands
// Since all root paths are hidden we need to show the directory
// anyway
bool isRootPath =
string.Compare(
string.Equals(
Path.GetPathRoot(path),
result.FullName,
StringComparison.OrdinalIgnoreCase) == 0;
StringComparison.OrdinalIgnoreCase);
// if "Hidden" is specified in the attribute filter dynamic parameters
// also return the object
@ -2140,7 +2140,7 @@ namespace Microsoft.PowerShell.Commands
// Check to see if the target specified is just filename. We dont allow rename to move the file to a different directory.
// If a path is specified for the newName then we flag that as an error.
if (string.Compare(Path.GetFileName(newName), newName, StringComparison.OrdinalIgnoreCase) != 0)
if (!string.Equals(Path.GetFileName(newName), newName, StringComparison.OrdinalIgnoreCase))
{
throw PSTraceSource.NewArgumentException(nameof(newName), FileSystemProviderStrings.RenameError);
}
@ -2858,10 +2858,10 @@ namespace Microsoft.PowerShell.Commands
string parentPath = GetParentPath(path, root);
if (!string.IsNullOrEmpty(parentPath) &&
string.Compare(
!string.Equals(
parentPath,
previousParent,
StringComparison.OrdinalIgnoreCase) != 0)
StringComparison.OrdinalIgnoreCase))
{
if (!ItemExists(parentPath))
{
@ -6339,7 +6339,7 @@ namespace Microsoft.PowerShell.Commands
if (member != null)
{
if (string.Compare(property.Name, "attributes", StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(property.Name, "attributes", StringComparison.OrdinalIgnoreCase))
{
FileAttributes attributes;

View file

@ -1719,20 +1719,20 @@ namespace System.Management.Automation
bool result = false;
if (string.Compare(
if (string.Equals(
driveName,
StringLiterals.Global,
StringComparison.OrdinalIgnoreCase) == 0)
StringComparison.OrdinalIgnoreCase))
{
// It's the global scope.
s_tracer.WriteLine("match found: {0}", StringLiterals.Global);
result = true;
scope = _sessionState.Internal.GlobalScope;
}
else if (string.Compare(
else if (string.Equals(
driveName,
StringLiterals.Local,
StringComparison.OrdinalIgnoreCase) == 0)
StringComparison.OrdinalIgnoreCase))
{
// It's the local scope.
s_tracer.WriteLine("match found: {0}", driveName);

View file

@ -432,10 +432,10 @@ namespace System.Management.Automation.Provider
// Check to see if the path is equal to the root
// of the virtual drive
if (string.Compare(
if (string.Equals(
path,
rootPath,
StringComparison.OrdinalIgnoreCase) == 0)
StringComparison.OrdinalIgnoreCase))
{
parentPath = string.Empty;
}

View file

@ -1521,10 +1521,10 @@ namespace Microsoft.PowerShell.Commands
{
// See if the paths are equal
if (string.Compare(
if (string.Equals(
sourcePath,
destinationPath,
StringComparison.OrdinalIgnoreCase) == 0)
StringComparison.OrdinalIgnoreCase))
{
result = true;
break;
@ -1539,10 +1539,10 @@ namespace Microsoft.PowerShell.Commands
break;
}
if (string.Compare(
if (string.Equals(
newDestinationPath,
destinationPath,
StringComparison.OrdinalIgnoreCase) == 0)
StringComparison.OrdinalIgnoreCase))
{
// We reached the root so the destination must not be a child
// of the source
@ -3203,8 +3203,8 @@ namespace Microsoft.PowerShell.Commands
}
if (string.IsNullOrEmpty(path) ||
(string.Compare(path, "\\", StringComparison.OrdinalIgnoreCase) == 0) ||
(string.Compare(path, "/", StringComparison.OrdinalIgnoreCase) == 0))
string.Equals(path, "\\", StringComparison.OrdinalIgnoreCase) ||
string.Equals(path, "/", StringComparison.OrdinalIgnoreCase))
{
result = true;
}

View file

@ -725,7 +725,7 @@ namespace System.Management.Automation
string logPipelineExecutionDetailsStr = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_LogPipelineExecutionDetails, false);
if (!string.IsNullOrEmpty(logPipelineExecutionDetailsStr))
{
if (string.Compare("1", logPipelineExecutionDetailsStr, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals("1", logPipelineExecutionDetailsStr, StringComparison.OrdinalIgnoreCase))
logPipelineExecutionDetails = true;
}