문제

누구든지 도와 줄 수 있고, 나는 일종의 일을하는 데 문제가 있었고, 나는 그것을 분류했다고 생각했지만 작동하지 않는 것처럼 보입니다.

다음 값을 저장하는 목록이 있습니다

8,6,10,11,7

또한 다른 목록이 있습니다 (수업에는 액세서리가 있으며 AccessoryID Current라는 속성이 있습니다. 클래스는 현재 6,7,8,10,11의 ID 순서입니다).

따라서 6,7,8,10,11에서 8,6,10,11,7의 간단한 목록에서 사용 된 순서로 분류해야합니다.

나는 내 incompartible (아래 참조)을 가지고 있으며 (아래 참조) 이렇게 부르고 있습니다. 입력하지만 목록에 여전히 모든 수업이 있지만 여전히 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);
도움이 되었습니까?

해결책

비교기가 정확합니다 (주석화 된 단일 라인 버전조차도). 문제는 ToList() 새로운 것을 만듭니다 List 요소의 사본을 포함합니다 IEnumerable<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));

다른 팁

Mehrdad는 목록이 정렬되지 않은 이유를 보여주었습니다. 비교 성능의 성능과 정렬 된 항목보다 정렬 항목이 적은 문제를 해결하고 싶습니다.

목록에서 indexof를 사용하여 색인을 찾는 것은 매우 비효율적입니다. 올바른 것을 찾기 위해 목록의 항목을 살펴 봐야합니다. 대신 사전을 조회로 사용하십시오. 그렇다면 항목을 한 번만 고리하십시오.

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);
   }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top