Odpowiedzi:
Możesz użyć metody 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
}
Array.IndexOfzależy Ci na kapitalizacji? Czy "text1" == "TEXT1"?
Array.IndexOfzwraca −1tylko wtedy, gdy indeks jest ograniczony do 0. Ta sprawa by się zepsuła, więc bądź świadomy! var a = Array.CreateInstance(typeof(int),new int[] { 2 }, new int[] { 1 }); a.SetValue(1, 1); Console.WriteLine(Array.IndexOf(a, 26)); // 0
var index = Array.FindIndex(stringArray, x => x == value)
Możemy również skorzystać z Exists:
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"));
charktórej nie można przekonwertować naSystem.Predicate<char>
EDYCJA: Nie zauważyłem, że również potrzebujesz tej pozycji. Nie można używać IndexOfbezpośrednio na wartości typu tablicowego, ponieważ jest on jawnie zaimplementowany. Możesz jednak użyć:
IList<string> arrayAsList = (IList<string>) stringArray;
int index = arrayAsList.IndexOf(value);
if (index != -1)
{
...
}
(Jest to podobne do wywołania Array.IndexOfzgodnie z odpowiedzią Darina - tylko alternatywne podejście. Nie jest dla mnie jasne, dlaczego jest zaimplementowane jawnie w tablicach, ale nieważne ...)IList<T>.IndexOf
if (months.Contains(model.Month))
Możesz użyć Array.IndexOf()- pamiętaj, że zwróci wartość -1, jeśli element nie został znaleziony i musisz sobie z tym poradzić.
int index = Array.IndexOf(stringArray, value);
możesz spróbować w ten sposób ... możesz użyć Array.IndexOf (), jeśli chcesz również znać pozycję
string [] arr = {"One","Two","Three"};
var target = "One";
var results = Array.FindAll(arr, s => s.Equals(target));
IMO najlepszym sposobem sprawdzenia, czy tablica zawiera podaną wartość, jest użycie System.Collections.Generic.IList<T>.Contains(T item)metody w następujący sposób:
((IList<string>)stringArray).Contains(value)
Kompletny przykład kodu:
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if (((IList<string>)stringArray).Contains(value)) Console.WriteLine("The array contains "+value);
else Console.WriteLine("The given string was not found in array.");
T[]tablice prywatnie implementują kilka metod List<T>, takich jak Count i Contains. Ponieważ jest to jawna (prywatna) implementacja, nie będzie można używać tych metod bez wcześniejszego rzutowania tablicy. To działa nie tylko w przypadku ciągów - możesz użyć tej sztuczki, aby sprawdzić, czy tablica dowolnego typu zawiera jakiś element, o ile klasa elementu implementuje IComparable.
Pamiętaj, że nie wszystkie IList<T>metody działają w ten sposób. Próba użycia IList<T>metody Add na tablicy nie powiedzie się.
Możesz tego spróbować, szuka indeksu zawierającego ten element i ustawia numer indeksu jako int, a następnie sprawdza, czy int jest większe niż -1, więc jeśli wynosi 0 lub więcej, to znaczy, że znalazł takie indeks - ponieważ tablice są oparte na 0.
string[] Selection = {"First", "Second", "Third", "Fourth"};
string Valid = "Third"; // You can change this to a Console.ReadLine() to
//use user input
int temp = Array.IndexOf(Selection, Valid); // it gets the index of 'Valid',
// in our case it's "Third"
if (temp > -1)
Console.WriteLine("Valid selection");
}
else
{
Console.WriteLine("Not a valid selection");
}
string x ="Hi ,World";
string y = x;
char[] whitespace = new char[]{ ' ',\t'};
string[] fooArray = y.Split(whitespace); // now you have an array of 3 strings
y = String.Join(" ", fooArray);
string[] target = { "Hi", "World", "VW_Slep" };
for (int i = 0; i < target.Length; i++)
{
string v = target[i];
string results = Array.Find(fooArray, element => element.StartsWith(v, StringComparison.Ordinal));
//
if (results != null)
{ MessageBox.Show(results); }
}
Stworzyłem metodę rozszerzenia do ponownego użycia.
public static bool InArray(this string str, string[] values)
{
if (Array.IndexOf(values, str) > -1)
return true;
return false;
}
Jak to nazwać:
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if(value.InArray(stringArray))
{
//do something
}
position, o co prosi PO?
string[] strArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if(Array.contains(strArray , value))
{
// Do something if the value is available in Array.
}
Najprostsza i krótsza metoda byłaby następująca.
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if(stringArray.Contains(value))
{
// Do something if the value is available in Array.
}
Containsmetody nie masz tych informacji