ユーザーが入力した多数の「製品名」を取得し、各製品に関する情報を取得するアプリケーションがあります。問題は、ユーザーが名前の一部または間違った名前を入力する可能性があるため、さらに選択するために最も近い一致を返したいということです。
基本的に、製品名 A がレコードと正確に一致する場合はそれを返し、そうでない場合は一致を含むものを返します。それ以外の場合は null を返します。
私はこれを 3 つの別々のステートメントで実行しましたが、これを行うためのより効率的な方法があるかどうか疑問に思っていました。LINQ to EF を使用していますが、パフォーマンス上の理由から、最初に製品をリストに具体化します。
productNames は、製品名のリストです (ユーザーが入力)。products は、製品の「レコード」のリストです
var directMatches = (from s in productNames
join p in products on s.ToLower() equals p.name.ToLower() into result
from r in result.DefaultIfEmpty()
select new {Key = s, Product = r});
var containsMatches = (from d in directMatches
from p in products
where d.Product == null
&& p.name.ToLower().Contains(d.Key)
select new { d.Key, Product = p });
var matches = from d in directMatches
join c in containsMatches on d.Key equals c.Key into result
from r in result.DefaultIfEmpty()
select new {d.Key, Product = d.Product ?? (r != null ? r.Product: null) };