尝试按枚举属性对对象列表进行排序

本文关键字:列表 排序 对象 枚举 属性 | 更新日期: 2023-09-27 18:17:08

我有一个如下的数据结构:

public enum Direction
{
  NONE, // SHOULD NEVER BE THIS
  UP,
  DOWN,
  LEFT,
  RIGHT
};
public struct dataStruct
{
   public Direction direction;
  public int CompareTo(dataStruct other)
  {
    return this.direction.CompareTo(other.direction);
  }
}

我将有一个dataStruct列表,我希望能够根据方向对它进行排序。因此,所有带UP的数据结构首先出现,然后是DOWN, LEFT,最后是RIGHT。

我试着用下面的代码来排序,

ListOfData.Sort(
  delegate(dataStruct obj1, dataStruct obj2)
  {
    return obj1.direction.CompareTo(obj2.direction);
  }
);

但是这给了我一个错误。我做错了什么吗?

编辑:我得到以下错误ArgumentException:没有实现正确的接口System.Collections.Generic.Comparer"1 + DefaultComparer [dataStruct]。比较(dataStruct x, dataStruct y)

尝试按枚举属性对对象列表进行排序

IComparable<dataStruct>添加到struct声明中

public struct dataStruct : IComparable<dataStruct>

然后执行

ListOfData.Sort()

试试这个:

var x = ListOfData.OrderByDescending
              (ListOfData => (Direction)Enum.Parse(typeof(Direction), ListOfData.Direction, true));

var x = ListOfData.OrderByDescending(i=> i.Direction);

如果您只需要按方向排序,这段简单的代码可以工作。你为什么需要CompareTo ?:

public class Program
{
    public void Main(string[] args)
    {
        List<dataStruct> objs = new List<dataStruct>(){
            new dataStruct{direction = Direction.DOWN, id=1},
            new dataStruct{direction = Direction.LEFT, id =2},
            new dataStruct{direction = Direction.UP, id =3},
        };
        var result = objs.OrderBy(x=>x.direction);
        foreach (var element in result)
        {
            Console.WriteLine ("{0}, {1}", element.direction, element.id);
        }
    }
}
public struct dataStruct
{
    public Direction direction;
    public int id;
    //other properties
}
public enum Direction
{
  NONE, // SHOULD NEVER BE THIS
  UP,
  DOWN,
  LEFT,
  RIGHT
};

您应该创建

public class DirectionComparer:IComparer<TypeOfData>
{
  public int Compare(dataStruct other)
  {
    return this.direction.CompareTo(other.direction);
  }
}

其中TypeOfData是ListOfData中元素的类型

并将其实例传递给sort方法。

ListOfData.Sort(new DirectionComparer());