1

誰でも助けてもらえますか、ソートに問題があります。ソートしたと思っていましたが、機能していないようです。

次の値を格納するリストがあります

8,6,10,11,7

私はまた別のリストを持っています(私のクラスのアクセサリーには現在accessoriesIdというプロパティがあり、クラスは現在6,7,8,10,11であるidの順序になっています)

したがって、それらを 6,7,8,10,11 から、8,6,10,11,7 という単純なリストから使用される順序に並べ替える必要があります。

私は icomparable を持っており (以下を参照)、このように呼び出しています - 入りますが、リストにはまだすべてのクラスが含まれていますが、まだ 6,7,8,10,11 の順序になっているため、何かが間違っています。

   // accesories is the IList<Accessories> (hence why i am use ToList)
   // and sortOrder is the simple int list list<int>
   accesories.ToList().Sort(new ItemTpComparer(sortOrder));  

class ItemTpComparer : IComparer<Accessories>
{
    private IList<int> otherList;

    public ItemTpComparer(IList<int> otherList)
    {
        this.otherList = otherList;
    }

    #region IComparer<Accessories> Members

    public int Compare(Accessories x, Accessories y)
    {

        if (otherList.IndexOf(x.AccessoryId) > otherList.IndexOf(y.AccessoryId))
            return 1;

        else if (otherList.IndexOf(x.AccessoryId) < otherList.IndexOf(y.AccessoryId))
            return -1;
        else
            return 0;

        // tried below also didn't work
        //return otherList.IndexOf(x.AccessoryId) - otherList.IndexOf(y.AccessoryId);
4

2 に答える 2

9

比較対象は正しいです(コメント付きの単一行バージョンでも)。問題は、オブジェクト内の要素のコピーを含むToList()新しいリストを作成することです。したがって、基本的には、新しいリストを作成し、それを並べ替えて破棄します。ListIEnumerable<T>

var sortedList = accesories.ToList();
sortedList.Sort(new ItemTpComparer(sortOrder)); 

次のように置き換えることをお勧めします:

var sortedList = accessories.OrderBy(sortOrder.IndexOf).ToList();

このように、比較器の実装は必要ありません。降順で簡単に並べ替えることもできます。

var sortedList = accessories.OrderByDescending(sortOrder.IndexOf).ToList();

オブジェクトが実際List<Accessories>にある場合は、その場で並べ替えることもできます。

((List<Accessories>)accessories).Sort(new ItemTpComparer(sortOrder));
于 2009-07-04T17:27:24.427 に答える
1

Mehrdad は、リストがソートされなかった理由を示しました。比較機能のパフォーマンスと、ソートされたアイテムよりもソートされたアイテムが少ないという問題にも対処したいと思います。

リストで IndexOf を使用してインデックスを見つけるのは非常に非効率的です。リスト内のアイテムをループして、正しいアイテムを見つける必要があります。代わりに辞書をルックアップとして使用して、アイテムを 1 回だけループします。

class ItemTpComparer : IComparer<Accessories> {

   private Dictionary<int, int> index;

   public ItemTpComparer(IList<int> otherList) {
      index = new Dictionary<int, int>();
      for (int i = 0; i < otherList.Count; i++) {
         index.Add(otherList[i], i);
      }
   }

   public int Compare(Accessories x, Accessories y) {
      return index[x.AccessoryId].CompareTo(index[y.AccessoryId]);
   }

}

並べ替える値のリストを並べ替える項目のリストよりも短くしたい場合は、値が辞書に存在するかどうかを確認します。

   public int Compare(Accessories x, Accessories y) {
      int xIndex, yIndex;
      if (!index.TryGetValue(x.AccessoryId, out xIndex)) xIndex = int.MaxValue;
      if (!index.TryGetValue(y.AccessoryId, out yIndex)) yIndex = int.MaxValue;
      return xIndex.CompareTo(yIndex);
   }
于 2009-07-04T18:32:24.167 に答える