1

*ユーザーが検索条件にワイルドカードを使用できる検索ページに取り組んでいます。ワイルドカードは、文字列の先頭または末尾に配置できます。これを適用する必要があるフィールドがいくつかあるため、拡張メソッドが最適な方法であると考えました。私が思いついたコードは現在動作しますが、IQueryable.

public static class Helper
{
    public static IEnumerable<string> MyExtMethod(this IEnumerable<string> items, string searchString)
    {
        var searchType = -1;    
        if(searchString.IndexOf("*") == -1) //No wildcard
        {
            searchType = 0;
        }
        else if(searchString.IndexOf("*") == 0 && searchString.LastIndexOf("*") == searchString.Length - 1)//start and end
        {
            searchType = 1;
        }
        else if(searchString.IndexOf("*") == 0)//ends with
        {
            searchType = 2;
        }
        else if(searchString.LastIndexOf("*") == searchString.Length - 1) //starts with
        {
            searchType = 3;
        }

        var search = searchString.Replace("*", "");

        foreach(var i in items)
        {
            switch(searchType)
            {
                case 0: yield return i;
                break;
                case 1: if(i.Contains(search))
                            yield return i;
                break;
                case 2: if(i.EndsWith(search))
                            yield return i;
                break;
                case 3: if(i.StartsWith(search))
                            yield return i;
                break;
            }
        }
    }
}

L2EContainsで既にサポートされている文字列操作と拡張メソッドのみを使用StartsWithしますEndsWith。これをエンティティで動作するように変換できますか? もしそうなら、何をする必要がありますか?ありがとう。

編集:可能であれば、これをそのまま使用できるようにしたいと思います:

db.SomeTable.Where(s => s.SomeField.MyExtMethod(somestring));

参照元のボーナス ポイント。

4

2 に答える 2