I want to take a user's input, and check if the end of what they put in ends with something. But it's more than one string. I have it in a list. And I could check if the input ends with a string from the list one by one. However, I would just like to check if the input ends with anything from a list.
Asked
Active
Viewed 1.0k times
19
-
1If the answer I provided below worked for you, please mark it as correct. – wablab Jun 15 '16 at 20:16
2 Answers
40
If "endings" is a List<string> that contains the possible endings to match:
if (endings.Any(x => userInput.EndsWith(x)))
{
// the string ends with something in the list
}

wablab
- 1,703
- 13
- 15
-
5is correct. if (endings.Any(userInput.EndsWith)) also works with less code. – Scope Creep Jun 12 '16 at 06:46
-
1Using this method you can ignore the case / use invariant culture etc which is useful: `endings.Any(x => userInput.EndsWith(x, StringComparison.InvariantCultureIgnoreCase)))` – SharpC May 26 '21 at 12:13
2
string[] imageEndsWith = { ".jpeg", ".JPEG", ".png", ".PNG", ".jpg", ".JPG" };
if (imageEndsWith.Any(x => _fileName.EndsWith(x))) {
//your code goes here
}
else {
}
what this code does is create an array of string(imageEndsWith) any of which you want to find at the end of another string(_fileName).
For example This code will find the jpeg or jpg or png images when the name of file is in the variable _fileName

Community
- 1
- 1

Jayant Rajwani
- 727
- 9
- 16
-
1While this code may answer the question, providing information on how and why it solves the problem improves its long-term value. – L_J Aug 20 '18 at 10:56
-
what this code does is create an array of string(imageEndsWith) any of which you want to find at the end of another string(_fileName). For example This code will find the jpeg or png images when the name if file is in the variable _fileName – Jayant Rajwani Aug 23 '18 at 11:17