[英]How to perform word search using LINQ?
我有一個包含供應商名稱的清單。 說
SuppId Supplier Name
----------------------------------
1 Aardema & Whitelaw
2 Aafedt Forde Gray
3 Whitelaw & Sears-Ewald
使用以下LINQ查詢
supplierListQuery = supplierListQuery.Where(x => x.SupplierName.Contains(SearchKey));
我可以在以下條件下正確返回記錄,
1)如果我使用搜索字符串作為“Whitelaw&Sears-Ewald” ,它將返回第3條記錄。
2)如果我使用“Whitelaw”或“ Sears-Ewald” ,它將返回第3條記錄。
但是,如果我將搜索字符串作為“Whitelaw Sears-Ewald”,我怎么能返回第3條記錄。 它總是返回0條記錄。
我可以使用ALL來獲得此結果,但我不知道如何使用它來滿足這一特殊需求。
在這種情況下我通常做的是將單詞拆分成一個集合,然后執行以下操作:
var searchopts = SearchKey.Split(' ').ToList();
supplierListQuery = supplierListQuery
.Where(x => searchopts.Any(y=> x.SupplierName.Contains(y)));
謝謝大家的快速回復。 但是那個有效或輕松解決這個問題的人是蒂莫西克利福德關於此的說明。 就像他說我改變了我對此的回答
string[] filters = SearchKey.ToLower().Split(new[] { ' ' });
objSuppliersList = (from x in objSuppliersList
where filters.All(f => x.SupplierName.ToLower().Contains(f))
select x).ToList();
現在它返回我所有serach條件的結果。
這對我有用:
IEnumerable<string> keyWords = SearchKey.Split('');
supplierListQuery = supplierListQuery
.AsParallel()
.Where
(
x => keyWords.All
(
keyword => x.SupplierName.ContainsIgnoreCase(keyword)
)
);
您需要使用某種字符串比較器來創建自己的簡單搜索引擎,然后您可以找到最有可能包含在結果中的字符串:
public static class SearchEngine
{
public static double CompareStrings(string val1, string val2)
{
if ((val1.Length == 0) || (val2.Length == 0)) return 0;
if (val1 == val2) return 100;
double maxLength = Math.Max(val1.Length, val2.Length);
double minLength = Math.Min(val1.Length, val2.Length);
int charIndex = 0;
for (int i = 0; i < minLength; i++) { if (val1.Contains(val2[i])) charIndex++; }
return Math.Round(charIndex / maxLength * 100);
}
public static List<string> Search(this string[] values, string searchKey, double threshold)
{
List<string> result = new List<string>();
for (int i = 0; i < values.Length; i++) if (CompareStrings(values[i], searchKey) > threshold) result.Add(values[i]);
return result;
}
}
用法示例:
string[] array = { "Aardema & Whitelaw", "Aafedt Forde Gray", "Whitelaw & Sears-Ewald" };
var result = array.Search("WhitelawSears-Ewald", 80);
// Results that matches this string with 80% or more
foreach (var item in result)
{
Console.WriteLine(item);
}
輸出: Whitelaw & Sears-Ewald
因為“Whitelaw”出現在兩者中,您將獲得兩個記錄。 否則沒有動態的方法來確定你只想要最后一個。 如果你知道你只有這3個,那么追加.Last()來獲得最終記錄。
supplierListQuery = supplierListQuery.Where(x => x.SupplierName.Contains(SearchKey.Split(' ')[0]));
如果你想要一個簡單(不是很方便)的解決方案,
var result = supplierListQuery
.Select(x => normalize(x.SupplierName))
.Where(x => x.Contains(normalize(SearchKey)));
string normalize(string inputStr)
{
string retVal = inputStr.Replace("&", "");
while (retVal.IndexOf(" ") >= 0)
{
retVal = retVal.Replace(" ", " ");
}
return retVal;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.