自定义IComparer for List(排序)的问题 - c#

mar*_*ith 1 c# sorting ilist list icomparer

任何人都可以帮助,我有问题做一个排序,我以为我已经排序但似乎没有工作.

我有一个存储以下值的List

8,6,10,11,7

我还有另一个List(我班上的配件,它有一个叫做accessoryId的属性,当前的类是id的顺序,当前是6,7,8,10,11)

因此,我需要将它们从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);
Run Code Online (Sandbox Code Playgroud)

Meh*_*ari 9

比较器是正确的(甚至是注释的单行版本).问题是在对象中ToList()创建一个List包含元素副本的new ,IEnumerable<T>因此基本上,您正在创建一个新列表,对其进行排序并将其丢弃.

var sortedList = accesories.ToList();
sortedList.Sort(new ItemTpComparer(sortOrder)); 
Run Code Online (Sandbox Code Playgroud)

我建议替换为:

var sortedList = accessories.OrderBy(sortOrder.IndexOf).ToList();
Run Code Online (Sandbox Code Playgroud)

这样,就不需要比较器实现了.您还可以轻松地按降序排序:

var sortedList = accessories.OrderByDescending(sortOrder.IndexOf).ToList();
Run Code Online (Sandbox Code Playgroud)

如果对象确实存在List<Accessories>,您还可以对其进行排序:

((List<Accessories>)accessories).Sort(new ItemTpComparer(sortOrder));
Run Code Online (Sandbox Code Playgroud)