Checking if a string array contains a value, and if so, getting its position

后端 未结 12 1088
日久生厌
日久生厌 2020-11-28 05:26

I have this string array:

string[] stringArray = { \"text1\", \"text2\", \"text3\", \"text4\" };
string value = \"text3\";

I would like to

12条回答
  •  清酒与你
    2020-11-28 06:00

    IMO the best way to check if an array contains a given value is to use System.Collections.Generic.IList.Contains(T item) method the following way:

    ((IList)stringArray).Contains(value)
    

    Complete code sample:

    string[] stringArray = { "text1", "text2", "text3", "text4" };
    string value = "text3";
    if (((IList)stringArray).Contains(value)) Console.WriteLine("The array contains "+value);
    else Console.WriteLine("The given string was not found in array.");
    

    T[] arrays privately implement a few methods of List, such as Count and Contains. Because it's an explicit (private) implementation, you won't be able to use these methods without casting the array first. This doesn't only work for strings - you can use this trick to check if an array of any type contains any element, as long as the element's class implements IComparable.

    Keep in mind not all IList methods work this way. Trying to use IList's Add method on an array will fail.

提交回复
热议问题