使用linq筛选类似项目的列表 [英] Filter list with linq for similar items

查看:117
本文介绍了使用linq筛选类似项目的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,可以根据Xaml的TextBox中输入的文本进行过滤.下面的代码过滤存储在results变量中的列表.该代码检查文本框输入(即queryString)是否与results列表中任何项目的Name完全匹配.这样只会从列表中带回字符串中与项目名称完全匹配的项目.

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.

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 similar to the queryString?

描述相似的意思是: 列表中的一个项目具有名称= Smirnoff伏特加酒.我想要这样,以便在文本框中输入"vodka"或"smirnoff"时,将返回项目Smirnoff Vodka.

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.

与上面的代码一样,要返回Smirnoff Vodka作为结果,必须在文本框中输入确切的名称"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.

推荐答案

这取决于您的意思,说相似"

It really depends on what you mean, by saying "similar"

选项:

1) var filteredItems = results.Where( p => p.Name != null && p.Name.ToUpper().Contains(queryString.ToUpper());

2)还有一种称为"Levenshtein距离"的算法:

2) There is also also known algorithm as "Levenshtein distance":

http://en.wikipedia.org/wiki/Levenshtein_distance

http://www.codeproject.com/Articles/13525/快速记忆有效的Levenshtein算法

最后一个链接包含c#中的源代码.通过使用它,您无法确定查询字符串与列表中的字符串的接近程度".

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.

这篇关于使用linq筛选类似项目的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆