你有一个对象列表,里面有两个整数。我想将此列表排序如下所示。
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)
答案 0 :(得分: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。
答案 1 :(得分:0)
一个简单的LINQ可以做!!
List<ListClass> lstSorted = (from element in listClassList
orderby element.rowIndex, element.columnIndex
select element).ToList();