简体   繁体   中英

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

The full error code:

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

  string[] terms = new string[31];

I'm trying to see if an array contains something in my Excel file. (Using Interop)

if (terms.Contains(xlWorkSheet.Cells[1, i1 + 1].Value.ToString())) ;
{

}

Why is Contains not working here?

I searched and apparently, it has something to do with the type not being the same, but in this case, it is. They are both strings.

Array ( string[] ) implements IList and therefore should have Contains(object o) method. But implementation is explicit , meaning that access to that method is possible only if class is treated as interface:

if (((IList)terms).Contains(xlWorkSheet.Cells[1, i1 + 1].Value.ToString()))

There is an extension method System.Linq.Enumerable.Contains .

string[] is an IEnumerable<string> so you can use this.

Add using System.Linq; to the top of the file to use it.

https://msdn.microsoft.com/en-us/library/system.linq.enumerable.contains(v=vs.110).aspx

You can use Array.Exists and pass a comparison lambda expression:

if (Array.Exists(terms, elem => elem == xlWorkSheet.Cells[1, i1 + 1].Value.ToString()))
{
    ...
}

Adding

using System.Linq; 

also helps

string[] unlike List<string> has no Contains() method. You'll need to run a loop through your array and compare each index.

for(int i = 0; i < terms.Length; i++)
{
    if (terms[i].Contains(xlWorkSheet.Cells[1, i1 + 1].Value.ToString()))
    {
        // do something
    }
}

However, instead of doing this I suggest you just use List<string> . With that you can use List.Contains() the same way you're trying to do in your example. In C# lists are superior to arrays in most cases.

The following will work:

using using System.Linq; //Added to top of code
...
...
string[] someList = {"First", "Second", "Third"}; //In your method

bool result = someList.Contains("First")) //equals true;
bool result2 = someList.Contains("Fourth")) //equals false;

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