string array.Contains?

2020-02-09 06:52发布

.NET 2

string[] myStrings = GetMyStrings();    
string test = "testValue";

How can I verify if myStrings contains test?

10条回答
倾城 Initia
2楼-- · 2020-02-09 07:13
bool ContainsString(string[] arr, string testval)
{
    if ( arr == null )
        return false;
    for ( int i = arr.Length-1; i >= 0; i-- )
        if ( arr[i] == testval )
            return true;
    return false;
}

And this will have the best performance ever. :P

查看更多
淡お忘
3楼-- · 2020-02-09 07:14

In .NET 2.0, you could do the following if you want the index:

int index = Array.FindIndex(
    myStrings,
    delegate(string s) { return s.Equals(test); }
);

index will be -1 if myStrings does not contain test.

If you merely want to check for existence:

bool exists = Array.Exists(
    myStrings,
    delegate(string s) { return s.Equals(test); }
);
查看更多
一夜七次
4楼-- · 2020-02-09 07:16

you can use Array.BinarySearch as described below.

 string[] strArray = GetStringArray();
        string strToSearch ="test";
        Array.BinarySearch(strArray, strToSearch);
查看更多
Melony?
5楼-- · 2020-02-09 07:20

I assume you want to check if any elements in your array contains a certain value (test). If so you want to construct a simple loop. In fact I think you should click here.

查看更多
【Aperson】
6楼-- · 2020-02-09 07:24

Thought I would add another to the mix, first available in .NET 3.5, I believe:

Enumerable.Contains(myStrings.ToArray(), test)
查看更多
够拽才男人
7楼-- · 2020-02-09 07:28

I have found an elegant answer at the page here http://www.dotnettoad.com/index.php?/archives/10-Array.Contains.html. What you have to do in .NET 2.0 is to cast to IList and call Contains method.

(IList<string> mystrings).Contains(test);
查看更多
登录 后发表回答