简体   繁体   中英

string[*,*] does not contain a definition for 'Contains'

I have a function that checks if a 2-dimensional string array contains a specific string value using .Contains . System.Linq is being used, as seems to be the problem in similar questions, however I still get the error of:

'string[ , ]' does not contain a definition for 'Contains' and the best extension method overload 'Queryable.Contains(IQueryable,string)' requires a receiver of type 'IQueryable'.

This error persists no matter what I change the comparison value to. The context for the error occuremce is as

string comparisonString = " "; 
bool victoryRequirement = mineArray.Contains(comparisonString);

I hope someone can tell me why this error occurs and whether or not I am able to use Contains for this purpose. I suspect the 2-dimensional array is partly at fault, but I am not that experienced.

Though the answer of Adil Mammodov appears to work, it is not very general. I would have preferred to write this as the much shorter and more flexible:

public static IEnumerable<T> ToSequence<T>(this T[,] items)
{
  return items.Cast<T>();
}

And now you can simply use ToSequence to turn an array into a sequence, and then apply a sequence operator to it.

myItems.ToSequence().Contains(target);

Also, while we're looking at your code: try to name things according to what they do, not what type they are. If you have "Array" and "String" in names of things, they could have better, more descriptive names. The type is already annotated in the type.

You can write your own contains method for two dimensional string array like below:

public bool TwoDimensionalContains(string[,] inputArray, string comparisonString)
{            
    for (int i = 0; i < inputArray.GetLength(0); i++)
    {
        for (int j = 0; j < inputArray.GetLength(1); j++)
        {                    
            // If matching element found, return true
            if (comparisonString.Equals(inputArray[i, j]))
                return true;
        }
    }
    // No matchincg element found, return false
    return false;
}

Then use it as below:

string[,] myArray = new string[2, 2]
{
    { "One", "Two" },
    {  "Three", "Four" }
};

bool contains = TwoDimensionalContains(myArray, "Three");

You can also make TwoDimensionalContains method, extension method to use it as other Linq methods.

Actually this works:

var c=myArray.Cast<string>().Select(x=>x).Contains("Three");

even easier:

var c=myArray.Cast<string>().Contains("Three");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM