0

次のコードをリファクタリングしようとしました(一部のデータベースレコードをカテゴリと検索用語でフィルタリングします)。

from entry in _DB.TheTable
join otherEntry in _DB.AnotherTable
on entry.PrimaryKey equals otherEntry.Field
where category.Any(String.IsNullOrWhiteSpace) 
   || category.Contains(entry.ProductGroup)
where String.IsNullOrWhiteSpace(searchTerm)
   || entry.ProductNumber.Contains(searchTerm)
   || otherEntry.Name1.Contains(searchTerm)
   || otherEntry.Name2.Contains(searchTerm)
   || otherEntry.Name3.Contains(searchTerm)
select new {entry.Something, entry.SomethingElse};

このように見えるように:

from entry in _DB.TheTable
join otherEntry in _DB.AnotherTable on entry.PrimaryKey equals otherEntry.Field
let searchFields = new[]{entry.ProductNumber, otherEntry.Name1, otherEntry.Name2,/*...*/}
where category.Any(String.IsNullOrWhiteSpace) 
   || category.Contains(entry.ProductGroup)
where String.IsNullOrWhiteSpace(searchTerm) 
   || searchFields.Any(field=>field.Contains(searchTerm))
select new {entry.Something, entry.SomethingElse};

残念ながら、LINQ to SQLはこれを実行できないようです。ArgumentExceptionコードから、次のようにsearchFields.Any(field=>field.Contains(searchTerm))記述されています。

引数valueのタイプが間違っていました。期待:System.String.実際:System.String[].

これを機能するように調整するにはどうすればよいですか?

編集:申し訳ありませんが、言及するのを忘れたのsearchTermstringcategoryですstring[]

4

2 に答える 2

0

編集:ここで与えられた解決策は正しくありません

あなたが抱えている問題は、Containsが文字列値しか取得できず、String[]を渡していることです。変数は文字列であり、それに含まれる値を探しているので、関数searchTerm.Contains(field)の条件を正しく設定するためにできるかもしれないと思い ます。これがお役に立てば幸いです。またね!AnyfieldsearchTerm

于 2012-07-18T08:46:40.933 に答える
0

私が見つけた唯一の回避策は、検索するすべてのフィールドを1つの文字列に連結し、検索語がその中に含まれているかどうかを確認することでした。もちろん、これは誤検知を返す可能性があり、それを防ぐためにフィールドの間に区切り文字を挿入する必要があります。

from entry in _DB.TheTable
join otherEntry in _DB.AnotherTable on entry.PrimaryKey equals otherEntry.Field
let searchFields = entry.ProductNumber + otherEntry.Name1 + otherEntry.Name2 
                   + otherEntry.Name3
where category.Any(String.IsNullOrWhiteSpace) 
        || category.Contains(entry.ProductGroup)
where String.IsNullOrWhiteSpace(searchTerm)
        || searchFields.Contains(searchTerm)
select new {entry.Something, entry.SomethingElse};

私はまだより良い解決策を開いており、それらが提供する場合は他の答えを受け入れます。その間、質問に示されている元のバージョンに戻りました。

于 2012-07-22T08:20:08.907 に答える