views:

155

answers:

3

Hi folks,

i'm trying to find out if a string value EndsWith another string. This 'other string' are the values from a collection. I'm trying to do this as an extension method, for strings.

eg.

var collection = string[] { "ny", "er", "ty" };
"Johnny".EndsWith(collection); // returns true.
"Fred".EndsWith(collection); // returns false.
+4  A: 
var collection = new string[] { "ny", "er", "ty" };

bool doesEnd = collection.Any(item => "Johnny".EndsWith(item));
doesEnd = collection.Any(item => "Fred".EndsWith(item));

You can convert it to an extension method

public static bool EndWith(this string value, IEnumerable<string> values)
{
    return values.Any(item => value.EndsWith(item));
}

EDIT by PK:

ReSharper says it can be refactored to:

bool doesEnd = collection.Any("Johnny".EndsWith);

public static bool EndWith(this string value, IEnumerable<string> values)
{
    return values.Any(value.EndsWith);
}

kewl :)

Pierre-Alain Vigeant
_ANY_ .. ah!!! awesome :) i love Linq. thanks mate :)
Pure.Krome
Weird syntax from reshaper
Pierre-Alain Vigeant
A: 

There is nothing built in to the .NET framework but here is an extension method that will do the trick:

public static Boolean EndsWith(this String source, IEnumerable<String> suffixes)
{
    if (String.IsNullOrEmpty(source)) return false;
    if (suffixes == null) return false;

    foreach (String suffix in suffixes)
        if (source.EndsWith(suffix))
            return true;

    return false;
}
Andrew Hare
Cheers andrew. yeah, this is (more or less) what i've already got. I was wanting to see how to do this as Linq (so I can learn it).
Pure.Krome
snap! hahahah :-)
Preet Sangha
A: 
public static class Ex{
 public static bool EndsWith(this string item, IEnumerable<string> list){
   foreach(string s in list) {
    if(item.EndsWith(s) return true;
   }
   return false;
 }
}
Preet Sangha