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"
                                       };

私はこのコンパレータを使用しようとしています:

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(new MatchComparer(searchTerm) を呼び出すと、リストの上部に「猫にノミがいます」という結果になります。

私はここで奇妙な/奇妙なことをしているに違いないと思います..ここで何か問題がありますか、それとも私がやろうとしていることに対するより良いアプローチがありますか?

ありがとう!

4

1 に答える 1

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
    } 
}
于 2011-09-12T23:52:45.320 に答える