누구든지 도움을받을 수 있습니다. 정렬 작업을 수행하는 데 문제가 있습니다. 정렬되었지만 작동하지 않는 것으로 보입니다.List (sort)에 대한 사용자 지정 IComparer 문제 - C#
나는 다음과 같은 값
8,6,10,11,7를 저장하는 목록이
나는 또한 다른 목록을(내 클래스의 액세서리는 accessoryId 전류 클래스라는 PROPERT있다 이드의 순서는 현재 6,7,8,10,11)
따라서 나는 그들을 6,7,8,10,11에서 간단한 목록에서 사용한 순서대로 정렬해야한다. , 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);
와우! 정말 감사합니다. .. "var sortedList = accesories.OrderBy (item => sortOrder.IndexOf (item.AccessoryId)) .ToList();" 또한 정렬 수가 적은 경우 (예 : 8,6 ..을 제공하고 정렬하는 경우) ... 훌륭합니다. 결과는 8,6이 결과 끝에 정렬됩니다. 가능합니까? 처음부터 8,6을 정렬하고 더 이상 일행이 없기 때문에 결국에는 나머지를 순서대로 정렬합니까? –
@mark smith : 존재하지 않는 항목에 대해서는'IndexOf'가 -1을 반환하기 때문입니다. 내림차순 정렬에 대한 대답을 업데이트하고 있습니다. –
큰 감사 ... 고정! –