The anonymous method you use will be converted to a Predicate<string> delegate by the compiler. With this in mind, you can enter local to get rid of unnecessary redundancy.
Predicate<string> containsStr = delegate(string s) { return s.Contains(str); }; if (list.Exists(containsStr)) { string name = list.Find(containsStr); ... }
In C # 3.0 or later, you can express it even more severely with lambda expressions.
Predicate<string> containsStr = s => s.Contains(str);
In another note, you do not need to check first whether str exists and then continue the search (if the list does not contain zeros), you can simply:
string name = list.Find(s => s.Contains(str)); if(name != null) {
Of course, I should also indicate that the strings do not contain extra metadata other than the characters present in them, so you donβt get anything by "finding" a string in the list, just checking if it exists (if you did not mean FindIndex ).
source share