2009-10-29 3 views
7

私は文字列値EndsWithが別の文字列かどうかを調べようとしています。この 'その他の文字列'は、コレクションの値です。私は文字列の拡張メソッドとしてこれをしようとしています。Linqを使って、この文字列が(コレクションの)値で終わるかどうかを調べるにはどうすればよいですか?

例えば、

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

答えて

12
var collection = new string[] { "ny", "er", "ty" }; 

var doesEnd = collection.Any("Johnny".EndsWith); 
var doesNotEnd = collection.Any("Fred".EndsWith); 

あなたはそこ.NETフレームワークに組み込まれたものは何もありませんが、ここではトリックを行います拡張メソッドであるAny

public static bool EndsWith(this string value, params string[] values) 
{ 
    return values.Any(value.EndsWith); 
} 

var isValid = "Johnny".EndsWith("ny", "er", "ty"); 
+0

_ANY_ ..ああ!すごい:)私はLinqが大好きです。おかげで仲間:) –

0

の使用を非表示にする文字列の拡張機能を作成することができます:

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; 
} 
+0

乾杯アンドリュー。ええ、これは(多かれ少なかれ)私がすでに持っているものです。私はLinqとしてこれを行う方法を見たいと思っていたので(私はそれを学ぶことができます)。 –

+0

スナップ! hahahah :-) –

0
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; 
} 
}