排序列需要IComparable

时间:2013-01-25 07:37:43

标签: c# devexpress xtragrid icomparable

我的DevExpress xtragrid中的一个列没有排序,分组或过滤。对类似问题的回答表明我需要实现IComparable,但是当我这样做时它根本不再显示在列中。

public class Flow : System.IComparable<Flow>
{
  public Flow(int id, string name, string description)
  {
    this.ID = id;
    this.Name = name;
    this.Description = description;
  }

  public int ID { get; private set; }

  public string Name { get; private set; }

  public string Description { get; private set; }

  public override string ToString()
  {
    return Name;
  }

  public override bool Equals(object obj)
  {
    Flow flow = obj as Flow;
    if (flow == null) return false;
    return this.ID == flow.ID;
  }

  public static bool operator ==(Flow flow1, Flow flow2)
  {
    if (object.ReferenceEquals(null, flow1))
      return object.ReferenceEquals(null, flow2);
    return flow1.Equals(flow2);
  }

  public static bool operator !=(Flow flow1, Flow flow2)
  {
    return !(flow1 == flow2);
  }

  public override int GetHashCode()
  {
    return ID;
  }

  public int CompareTo(Flow other)
  {
    return this.Name.CompareTo(other.Name);
  }
}

我做错了什么?

更新

DevExpress ......

2 个答案:

答案 0 :(得分:2)

消失的内容是一个无关的问题 - 红鲱鱼。在我实施IComparable而不是IComparable<Flow>

后,该列允许排序
public int CompareTo(object obj)
{
  if (object.ReferenceEquals(null, obj))
    return 1;
  Flow flow = obj as Flow;
  if (flow == null)
    throw new ArgumentException("Object is not of type Flow");
  return this.Name.CompareTo(flow.Name);
}

来自IComparable.CompareTo Method

的MSDN文档

答案 1 :(得分:0)

看起来你的CompareTo方法是错误的。尝试将以下内容添加到CompareTo()方法中,看看它是否正常工作:

    public int CompareTo(Flow other)
    {
      // Alphabetic sort if name is equal.
      if this.Name == other.Name
      {
        return this.Name.CompareTo(other.Name);
      }
     //Default sort.
     return other.Name.CompareTo(this.Name);
    }

让我知道它是否解决了你的问题。