2009-06-30 68 views
0

我一直在研究C#中的Access文件编辑器,并且我一直在尝试将一个搜索功能添加到我的程序中。到目前为止,我有数据库文件填充一个二维数组,然后我用它来填充另一个窗口中的ListView框。在这个新窗口中,我希望能够按照型号搜索每个条目。到目前为止,我已经设法合并Levenstein算法,这似乎有很多用处。我可以使用算法来分配每个条目和搜索键盘之间的距离值,并将该值分配给另一个整数数组。我也可以按升序排列结果。使用Levenstein对字符串数组进行排序算法结果

但是,我目前的问题是,我希望将模型号码与莱文斯坦算法的距离值相同的方式排序,以便最相关的结果成为ListView框中的第一个选项。任何想法任何人??!?!

这里是我到目前为止有:

private void OnSearch(object sender, System.EventArgs e) 
    { 

     string a; 
     string b; 
     int[] result = new int[1000]; 
     int[] sorted = new int[1000]; 

      for (int i = 0; i < rowC; i++) 
      { 
       a = PartNum[i];   // Array to search 
       b = SearchBox1.Text;  // keyword to search with 

       if (GetDistance(a, b) == 0) 
       { 
        return; 
       } 

       result[i] = GetDistance(a, b); //add each distance result into array 

      } 

      int index; 
      int x; 

      for (int j = 1; j < rowC; j++)  //quick insertion sort 
      { 
       index = result[j]; 
       x = j; 

       while ((x > 0) && (result[x - 1] > index)) 
       { 
        result[x] = result[x - 1]; 
        x = x - 1; 
       } 
       result[x] = index; 
      } 

     } 


    public static int GetDistance(string s, string t) 
    { 
     if (String.IsNullOrEmpty(s) || String.IsNullOrEmpty(t)) 
     { 
      MessageBox.Show("Please enter something to search!!"); 
      return 0; 

     } 

     int n = s.Length; 
     int m = t.Length; 
     if (n == 0) 
     { 
      return m; 
     } 

     else if (m == 0) 
     { 
      return n; 
     } 

     int[] p = new int[n + 1]; 
     int[] d = new int[n + 1]; 
     int[] _d; 
     char t_j; 
     int cost; 

     for (int i = 0; i <= n; i++) 
     { 
      p[i] = i; 
     } 

     for (int j = 1; j <= m; j++) 
     { 
      t_j = t[j - 1]; 
      d[0] = j; 

      for (int i = 1; i <= n; i++) 
      { 
       cost = (s[i - 1] == t_j) ? 0 : 1; 
       d[i] = Math.Min(Math.Min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost); 
      } 
      _d = p; 
      p = d; 
      d = _d; 
     } 
     return p[n]; 
    } 

回答

0

你有LINQ提供给你?如果是这样的:

var ordered = PartNum.OrderBy(x => GetDistance(x, SearchBox1.Text)) 
        .ToList(); 

// Do whatever with the ordered list 

请注意这个,如果你找到一个精确匹配不及早中止,以及不使实际距离可用的缺点 - 但你是如何使用的结果反正不是完全清楚...

另一种选择是:

var ordered = (from word in PartNum 
       let distance = GetDistance(word, SearchBox1.Text)) 
       orderby distance 
       select new { word, distance }).ToList(); 

那么你已经有了距离为好。

+0

如何使用第二个选项并插入TakeWhile()?你最终有这样的事情: “...})。TakeWhile(i => i.distance!= 0).ToList();” 然后,您可以检查最后一个索引并使用它,或者之后进行排序。 – 2009-06-30 20:03:02

0

为了按Levenstein距离对数组进行排序,您需要将模型数字作为数组的一部分,以便在按Levenstein数字对数组进行排序时,模型数字会随之而来。

为此,创建一个类表示每个部分:

public class Part 
{ 
    public string PartNumber; 
    public int LevensteinDistance; 
} 

,然后创建部分的数组:

Part[] parts; 

然后可以参考每个元素像这样:

parts[n].LevensteinDistance 
parts[n].PartNumber 
相关问题