1

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

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)

4

2 回答 2

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

于 2012-08-03T10:13:44.177 回答
0

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

List<ListClass> lstSorted = (from element in listClassList
                             orderby element.rowIndex, element.columnIndex
                             select element).ToList();
于 2012-08-03T11:04:09.777 回答