【问题标题】:Find similar product using linq使用 linq 查找类似产品
【发布时间】:2020-12-12 18:06:42
【问题描述】:

我有一份产品清单。 当我在使用 linq 的产品页面中时,我想选择一些类似的产品。 例如,我在“美国英语文件预中级”页面。 我在 db 中有一些产品,如下所示:

  • 美式英语文件预中级
  • 美式英语文件中级
  • 美式英语文件高级版
  • 美式英语文件高级版
  • 美式英语文件初学者

我想做什么:

  • 将“美式英语文件预中级”拆分为字符串[]。
  • 我为 string[] 的大小定义了 int totalCount。
  • 过滤长度大于 3 的单词(以消除一些单词,例如 'the' 、'and'、'or' 、...)
  • 那么我想选择标题中至少有(2 个或 totalCount-1)个常用词和拆分词的产品。
  • 以下是我用来测试具有两个列表的解决方案的内容。但我不喜欢使用 2 列表。
List<string> list = new List<string>();
List<string> list2 = new List<string>();
list.Add("english file pre-intermediate 2 the");
list.Add("english file intermediate 2 the");
list.Add("english file pre-advanced 2 the");
list.Add("english file advanced 2 the");
list.Add("english file beginner 2 the");
list.Add("english file");
list.Add("english file beginner 2 the");
list.Add("english file");
var words = textBox1.Text.Split(' ');
label1.Text = words.Length.ToString();
string res = "";
foreach (var item in words)
{
    if (item.Length>3)
    {
        res = res + "-";
    }
}

int total = words.Where(p => p.Length > 3).Count();
var fwords = words.Where(p => p.Length > 3).OrderBy(p=>p);

foreach (var item in list)
{
    int i = 0;
    int j = 0;
    foreach (var w in fwords)
    {
        if (item.ToLower().Contains(w.ToLower()))
        {
            j++;
        }
        else
        {
            i--;
        }
        
    }

    if (i>=-1 && j>=2)
    {
        list2.Add(item);
    }
}

var res2 = "";
foreach (var item in list2)
{
    res2 = res2 + item + "---";
}
label2.Text = res2;

【问题讨论】:

  • 尝试模糊匹配,例如github.com/JakeBayer/FuzzySharp
  • var res = words.Where( w =&gt; w.Length&gt; 3).Aggregate("-",(current, next)=&gt; current + "-" );
  • int total = res.Length;

标签: c# asp.net sql-server linq model-view-controller


【解决方案1】:

如果你想使用 Linq,你可以这样做:

// setup
var products = new List<string>
{
    "American English File Pre-intermediate",
    "British English Word Intermediate",
    "American English File Pre-Advanced",
    "British English Word Pre-Advanced",
    "British English File Beginner"
};
var currentProductPage = products[0];

// split and filter short words
var currentProductWords = currentProductPage.Split(' ').Where(product => product.Length > 3);

// Find two ore more matching words
var productsMatchingTwoOrMoreWords = products.Where(product => product.Split(' ').Intersect(currentProductWords).Count() >= 2);

// Display result
foreach (var matchingProducts in productsMatchingTwoOrMoreWords)
{
    Console.WriteLine(matchingProducts);
}

首先你拆分当前产品页面并过滤掉短词。
然后查看所有产品并:

  • 你拆分了产品
  • 您可以使用 intersect 找到匹配的单词
  • 您过滤了 2 个或更多匹配词

您必须小心使用这种方法,因为它可能会对性能造成很大影响。
如果您需要多次执行此操作,最好单独保存单词。然后你只需要拆分当前页面并与之进行比较。
如果您有很多产品要搜索,也要小心。

【讨论】:

  • 这正是我想要的。非常感谢@-}--
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多