Search code examples
c#.netsonarqube

Collection-specific "Exists" method should be used instead of the "Any" extension error


In my organization the sonarqube scanner has been added and in testing it gives an error (the one in the title):

Collection-specific "Exists" method should be used instead of the "Any" extensioncsharpsquid:S6605

This the code

private static Variables[] MapVaraiblesHome(Property? property, Variables[] variables)
{
    foreach (var variabile in variables.Where(variabile => VariablesDataConstants.PropertyMap.ContainsKey(variabile.VariablesData?.Code!)))
    {
        if (!(variabile.VariablesData!.Code == "A47O" || variabile.VariablesData.Code == "FF78O"))
        {
            variabile.Values = GetValueRecursive(property!, VariablesDataConstants.PropertyMap[variabile.VariablesData?.Code!].Path);
        }
        else
        {
            variabile.Values = Convert.ToInt32(GetValueRecursive(property!, VariablesDataConstants.PropertyMap[variabile.VariablesData.Code].Path));
        }
    }

    return
        [
        .. variables,
        .. VariablesDataConstants.PropertyMap.Where(p => !variables.Any(v => v.VariablesData?.Code == p.Key)).Select(elem => {
            return new Variables
            {
                VariableData = new VariableDataGeneric
                {
                    Code = elem.Key,
                    Description = elem.Value.Description,
                },
                Values = GetValueRecursive(property!, elem.Value.Path),
            };
        })
        ];
}

I tried replacing Any with Exists but I get errors (the method as parameters wants an array and the predicate) and I try this:

!variables.Exists(variables,v => v.VariablesData?.Code == p.Key)

But I get error CS0176 Static member 'member' cannot be accessed with an instance reference; qualify it with a type name instead

Any solution?


Solution

  • Because Exists method is static method on Array class.

    Correct usage:

    !Array.Exists(variables, v => v.VariablesData?.Code == p.Key)
    

    Or, if you meant Exists method on List<T> class, which is not static, then you need to have List first:

    !variables.ToList().Exists(variables,v => v.VariablesData?.Code == p.Key)
    

    UPDATE

    Accordingly to documentation linked in comments, it should be changed to Array.Exists(...);