2011-09-12 17 views
0

我正在尝试编写自定义比较器来根据相似性对搜索结果列表进行排序。我希望最类似于输入搜索词的术语在列表中首先出现,然后是以搜索短语开头的短语,然后是按字母顺序排列的所有其他值。针对参数失败的自定义比较器

鉴于这种测试代码:

string searchTerm = "fleas"; 
    List<string> list = new List<string> 
             { 
              "cat fleas", 
              "dog fleas", 
              "advantage fleas", 
              "my cat has fleas", 
              "fleas", 
              "fleas on my cat" 
             }; 

我试图用这个的Comparer:

public class MatchComparer : IComparer<string> 
{ 
    private readonly string _searchTerm; 

    public MatchComparer(string searchTerm) 
    { 
     _searchTerm = searchTerm; 
    } 

    public int Compare(string x, string y) 
    { 
     if (x.Equals(_searchTerm) || 
      y.Equals(_searchTerm)) 
      return 0; 

     if (x.StartsWith(_searchTerm) || 
      y.StartsWith(_searchTerm)) 
      return 0; 

     if (x.Contains(_searchTerm)) 
      return 1; 

     if (y.Contains(_searchTerm)) 
      return 1; 

     return x.CompareTo(y); 
    } 

调用list.Sort(新MatchComparer(SEARCHTERM)会导致 '我的猫有跳蚤'在

列表的顶部。我想我必须做一些奇怪/这里怪异。是什么错在这里或者是有什么我试图做一个更好的方法?

谢谢!

回答

2

您没有使用所有可能的返回值的的CompareTo

-1 == X第一 0 ==相等 1 == y个第一你要

更多的东西像这样

public class MatchComparer : IComparer<string> 
{ 
    private readonly string _searchTerm; 

    public MatchComparer(string searchTerm) 
    { 
     _searchTerm = searchTerm; 
    } 

    public int Compare(string x, string y) 
    { 
     if (x.Equals(y)) return 0; // Both entries are equal; 
     if (x.Equals(_searchTerm)) return -1; // first string is search term so must come first 
     if (y.Equals(_searchTerm)) return 1; // second string is search term so must come first 
     if (x.StartsWith(_searchTerm)) { 
      // first string starts with search term 
      // if second string also starts with search term sort alphabetically else first string first 
      return (y.StartsWith(_searchTerm)) ? x.CompareTo(y) : -1; 
     }; 
     if (y.StartsWith(_searchTerm)) return 1; // second string starts with search term so comes first 
     if (x.Contains(_searchTerm)) { 
      // first string contains search term 
      // if second string also contains the search term sort alphabetically else first string first 
      return (y.Contains(_searchTerm)) ? x.CompareTo(y) : -1; 
     } 
     if (y.Contains(_searchTerm)) return 1; // second string contains search term so comes first 
     return x.CompareTo(y); // fall back on alphabetic 
    } 
} 
+0

太棒了!这似乎工作。谢谢 ! – duckus