首页 > 解决方案 > 如何在 2 或 3 分钟内比较大量字符串

问题描述

我有两个类或数组。A类有str1、str2、str3、str4、str5、str6。A 有 200,000。B 类有 St1、St2、St3、St4、St5、St6。有 50,000 个 B 类。如果 str1=St1 且 str2=St2,则将字符串添加到 Product 中,该字符串具有 str1、str2、str3、str4、str5、str6、St3、St4、St5、St6。

最简单的方法是有两个循环,但确实需要很长时间,我以前在6-8小时内完成。后来我尝试在excel中做同样的事情。我可以在大约 5 分钟内完成。但有时如果有人使用 excel 会出错。所以我想知道我是否仍然可以在不使用excel的情况下在后面的代码中做到这一点。

 Dim Products As ObservableCollection(Of Product)
    Dim lstProducts As New List(Of Product)

    for i=0 to ClassA.count-1
    for j=0 to ClassB.count-1
    if ClassA.item(i).str1 = ClassB.item(j).St1 and ClassA.item(i).str2 = ClassB.item(j).St2
    then 
    Dim p As New Product(str1, str2, str3, str4, str5, str6, St3, St4, St5, St6)
else
     Dim p As New Product(str1, str2, str3, str4, str5, str6, "", "", "", "")
    lstProducts.Add(p)
    end if
    next j
    next i

    Products = New ObservableCollection(Of Product)(lstProducts)

标签: c#vb.net

解决方案


对于ClassB,创建一个Dictionary,其中键是一对:(St1, St2),值是来自 的项目列表ClassB。对于每个(St1, St2),它存储所有ClassB具有这些St1和的项目St2。现在您应该只遍历ClassA,并且使用字典,您可以快速从ClassB.

运行时间线性取决于输入和输出的大小。

对不起,我不懂VB,所以我不会写代码。


推荐阅读