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

时间:2015-10-12 05:30:32

标签: c# list sorting

我有如下数据结构:

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列表,我希望能够根据Direction对其进行排序。所以带UP的所有dataStruct都是第一个,然后是DOWN,LEFT,最后是RIGHT。

我尝试使用以下代码对其进行排序,

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

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

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

4 个答案:

答案 0 :(得分:2)

IComparable<dataStruct>添加到结构声明。

public struct dataStruct : IComparable<dataStruct>

然后执行

ListOfData.Sort()

答案 1 :(得分:1)

试试这个:

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

或只是

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

答案 2 :(得分:1)

如果你只需要按方向排序,这个简单的代码就可以了。为什么需要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
};

答案 3 :(得分:0)

你应该创建

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

其中TypeOfData是ListOfData

中的元素类型

并将它的instatnce传递给sort方法。

ListOfData.Sort(new DirectionComparer());