0

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.

geothachankary
  • 1,040
  • 1
  • 17
  • 30
Marc
  • 3
  • 1
  • 2

3 Answers3

13

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.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • 1
    It is possible to generalize my method by implementing generics, but this is way better and deserves to be accepted answer. – Adil Mammadov Sep 25 '16 at 15:00
2

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.

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
Adil Mammadov
  • 8,476
  • 4
  • 31
  • 59
1

Actually this works:

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

even easier:

var c=myArray.Cast<string>().Contains("Three");
LoztInSpace
  • 5,584
  • 1
  • 15
  • 27