C# 使用 linq 过滤类似项目的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19627465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter list with linq for similar items
提问by Tester
I have a list in which I filter, according to the text input in a TextBox in Xaml. The code below filters the List stored in the results
variable. The code checks if the textbox input,ie, queryString
, matches the Name
of any item in the results
list EXACTLY. This only brings back the items from the list where the string matches the Name of a the item exactly.
我有一个列表,根据 Xaml 中 TextBox 中的文本输入进行过滤。下面的代码过滤存储在results
变量中的 List 。该代码检查文本框输入,即queryString
,是否与列表中Name
的任何项目results
完全匹配。这只会从列表中带回字符串与项目名称完全匹配的项目。
var filteredItems = results.Where(
p => string.Equals(p.Name, queryString, StringComparison.OrdinalIgnoreCase));
How do I change this so that it returns the items in the list whose Name
, is similarto the queryString?
如何更改它以返回列表Name
中与queryString相似的项目?
To describe what I mean by Similar: An item in the list has a Name= Smirnoff Vodka. I want it so that if "vodka" or "smirnoff" is entered in the textbox, the the item Smirnoff Vodka will be returned.
描述我所说的类似的意思:列表中的一个项目有一个 Name= Smirnoff Vodka。我希望这样,如果在文本框中输入“vodka”或“smirnoff”,将返回 Smirnoff Vodka 项。
As it is with the code above, to get Smirnoff Vodka returned as a result, the exact Name "Smirnoff Vodka" would have to be entered in the textbox.
与上面的代码一样,要返回 Smirnoff Vodka,必须在文本框中输入确切的名称“Smirnoff Vodka”。
采纳答案by Vladimir Gondarev
It really depends on what you mean, by saying "similar"
这真的取决于你的意思,说“相似”
Options:
选项:
1) var filteredItems = results.Where( p => p.Name != null && p.Name.ToUpper().Contains(queryString.ToUpper());
2) There is also also known algorithm as "Levenshtein distance":
2)也有一种称为“Levenshtein distance”的算法:
http://en.wikipedia.org/wiki/Levenshtein_distance
http://en.wikipedia.org/wiki/Levenshtein_distance
http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm
http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm
The last link contains the source code in c#. By using it you cann determine "how close" the query string to the string in your list.
最后一个链接包含 c# 中的源代码。通过使用它,您可以确定查询字符串与列表中字符串的“接近程度”。
回答by Saritha.S.R
Try this:
尝试这个:
fileList.Where(item => filterList.Contains(item))
回答by Ned Stoyanov
Try this:
尝试这个:
var query = "Smirnoff Vodka";
var queryList = query.Split(new [] {" "}, StringSplitOptions.RemoveEmptyEntries);
var fileList = new List<string>{"smirnoff soup", "absolut vodka", "beer"};
var result = from file in fileList
from item in queryList
where file.ToLower().Contains(item.ToLower())
select file;