How to search a Substring in String array in C#

前端 未结 4 696
予麋鹿
予麋鹿 2021-01-13 09:55

How to search for a Substring in String array? I need to search for a Substring in the string array. The string can be located in any part of the array (element) or within

4条回答
  •  猫巷女王i
    2021-01-13 10:23

    If you need the Index of the first element that contains the substring in the array elements, you can do this...

    int index = Array.FindIndex(arrayStrings, s => s.StartsWith(lineVar, StringComparison.OrdinalIgnoreCase)) // Use 'Ordinal' if you want to use the Case Checking.
    

    If you need the element's value that contains the substring, just use the array with the index you just got, like this...

    string fullString = arrayStrings[index];
    

    Note: The above code will find the first occurrence of the match. Similary, you can use Array.FindLastIndex() method if you want the last element in the array that contains the substring.

    You will need to convert the array to a List and then use the ForEach extension method along with Lambda expressions to get each element that contains the substring.

提交回复
热议问题