gpt4 book ai didi

c# - 使用 linq 查找类似产品

转载 作者:行者123 更新时间:2023-12-04 09:01:14 25 4
gpt4 key购买 nike

我有一个产品 list 。
当我在使用 linq 的产品页面中时,我想选择一些类似的产品。
例如,我在“American English File Pre-intermediate”页面。
我在数据库中有一些产品,如下所示:

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

  • 我试图做的事情:
  • 将 'American English File Pre-intermediate' 拆分为 string[]。
  • 我为 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;

    最佳答案

    如果你想使用 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);
    }
    首先,您拆分当前产品页面并过滤掉短词。
    然后你浏览所有产品并:
  • 您拆分产品
  • 你使用交集找到匹配的词
  • 您过滤了 2 个或更多匹配的词

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

    关于c# - 使用 linq 查找类似产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63555293/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com