C# Determing whether any element in a string array contains a given string anywhere
I have a string array:
string[] Animals = {"Cat", "Dog", "Fish"};
I then want to determine which element contains the sequence "is" and return that entire element; in this case "fish"
If I want to find "gh", it does not exist in the list, so it should return the first element, in this case "Cat"
I've tried this linq code, but i don't think I'm doing the lambda part right.
int index = Animals.Where(x => x.IndexOf("is") >= 0).First().IndexOf("is")
string result = index > 0 ? Animals[index] : Animals[0];
This code throws this开发者_如何学运维 error:
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: value
I think I'm close, I just can't seem to get it.
This method obviously isn't fool proof, it should return the first instance of "is" which could be problematic. My potential list is fairly small and the index word is always unique.
Try this:
string result = Animals.FirstOrDefault(x => x.Contains("is")) ?? Animals.First();
(This will fail if the array contains no elements; what do you want to do in this case? You could try FirstOrDefault
for the fallback expression as well - this will return null
if the sequence is empty.)
Given your requirements, the code you posted has 2 issues:
- It uses
Enumerable.First
, which will throw an exception on an empty sequence i.e. if no item exists that matches the original predicate. - The index you are using in the the second statement is the index of the "is" substring in the result of the first query, not the index of the result in the original array. Consequently, it does not make sense to use that number to index the original array.
精彩评论