【问题标题】:Sorting List which has object that contains two integer members具有包含两个整数成员的对象的排序列表
【发布时间】:2012-08-03 19:04:09
【问题描述】:

你有一个包含两个整数的对象列表。我想对该列表进行排序,如下所示。

public class ListClass
{
    public int rowIndex { get; set; }
    public int columnIndex { get; set; }
    public ListClass()
    {
    }

    public ListClass(int row, int column)
    {
        this.rowIndex = row;
        this.columnIndex = column;
    }
}

public static void main()
{
    List<ListClass> listClassList = new List<ListClass>();
    listClassList.Add(new ListClass(0,1));
    listClassList.Add(new ListClass(0,3));
    listClassList.Add(new ListClass(0,2));
    listClassList.Add(new ListClass(0,8));
    listClassList.Add(new ListClass(1,1));
    listClassList.Add(new ListClass(1,0));
    listClassList.Add(new ListClass(2,1));
    listClassList.Add(new ListClass(3,0));
    listClassList.Add(new ListClass(3,8));
    listClassList.Add(new ListClass(3,3));
    listClassList.Add(new ListClass(3,1));
    listClassList.Sort();
}
public void Sort()
{
    \\Help Here
}


排序后这个列表应该是这样的。 (0,1)
(0,2)
(0,3)
(0,8)
(1,0)
(1,1)
(2,1)
(3,0)
(3,1)
(3,3)
(3,8)

【问题讨论】:

    标签: list


    【解决方案1】:

    如下更改 ListClass 以使用 IComparable...

    public class ListClass : IComparable<ListClass>
    {
        public int rowIndex { get; set; }
        public int columnIndex { get; set; }
    
        public ListClass(int row, int column)
        {
            this.rowIndex = row;
            this.columnIndex = column;
        }
    
        public int CompareTo(ListClass other)
        {
            var index = this.rowIndex.CompareTo(other.rowIndex);
            return index == 0 ? this.columnIndex.CompareTo(other.columnIndex) : index;
        } 
    }
    

    调用 listClassList.Sort();现在将按要求对列表进行排序。

    更多信息请参见IComparable。

    【讨论】:

      【解决方案2】:

      一个简单的 LINQ 就可以做到!

      List<ListClass> lstSorted = (from element in listClassList
                                   orderby element.rowIndex, element.columnIndex
                                   select element).ToList();
      

      【讨论】:

      • 非常感谢它真的有帮助.. :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      相关资源
      最近更新 更多