MoS*_*She 152 c# arrays string
我有这个字符串数组:
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
Run Code Online (Sandbox Code Playgroud)
我想确定是否stringArray包含value.如果是这样,我想找到它在数组中的位置.
我不想使用循环.谁能建议我怎么做?
Dar*_*rov 294
您可以使用Array.IndexOf方法:
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos > -1)
{
// the array contains the string and the pos variable
// will have its position in the array
}
Run Code Online (Sandbox Code Playgroud)
BLU*_*IXY 68
var index = Array.FindIndex(stringArray, x => x == value)
Run Code Online (Sandbox Code Playgroud)
Tar*_*ran 27
我们也可以使用存在
string[] array = { "cat", "dog", "perl" };
// Use Array.Exists in different ways.
bool a = Array.Exists(array, element => element == "perl");
bool c = Array.Exists(array, element => element.StartsWith("d"));
bool d = Array.Exists(array, element => element.StartsWith("x"));
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 13
编辑:我没有注意到你也需要这个位置.您不能IndexOf直接使用数组类型的值,因为它是显式实现的.但是,您可以使用:
IList<string> arrayAsList = (IList<string>) stringArray;
int index = arrayAsList.IndexOf(value);
if (index != -1)
{
...
}
Run Code Online (Sandbox Code Playgroud)
(这类似于调用Array.IndexOf按照达林的答案-只是一种替代方法,为什么这不是很清楚,我是在阵列中明确实现,但没关系...)IList<T>.IndexOf
你可以使用Array.IndexOf()- 请注意,如果找不到元素,它将返回-1,你必须处理这种情况.
int index = Array.IndexOf(stringArray, value);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
350984 次 |
| 最近记录: |