我正在写一个地址簿程序。我将每个人的详细信息存储在List<Person>
中。我需要能够按姓氏(如果有关系使用名字)或邮政编码对此列表进行排序。
到目前为止,我有这个:
public class Person
{
public string LastName { get; set; }
public string FirstName { get; set; }
public string PostCode { get; set; }
// etc..
}
public class AddressBook
{
public List<Person> People { get; set; }
// asc: ascending or descending
// column: the property to use when sorting
// (in my case either LastName or Postcode)
public void Sort(bool asc, string column)
{
// What should I put here?
}
// etc...
}
我尝试过使用ICompare
和IComparable
接口,但我只是没有得到它。
如何编写Sort
方法?
答案 0 :(得分:4)
您可以尝试使用LINQ扩展方法OrderBy
,OrderByDescending
,ThenBy
和ThenByDescending
:
using System.Linq;
// ...
public void Sort(bool asc, string column)
{
switch (column)
{
case "LastName":
People = People.OrderBy(x => x.LastName).ThenBy(x => x.FirstName).ToList();
break;
case "PostCode":
People = People.OrderBy(x => x.PostCode).ToList();
break;
default:
// error handling
}
if (!asc)
{
People.Reverse();
}
}
您还可以查看动态LINQ,它将简化此代码。
答案 1 :(得分:3)
您可以使用IComparer<T>
的实现:
public class PersonComparer : IComparer<Person>
{
private readonly bool _sortAscending;
private readonly string _columnToSortOn;
public PersonComparer(bool sortAscending, string columnToSortOn)
{
_sortAscending = sortAscending;
_columnToSortOn = columnToSortOn;
}
public int Compare(Person x, Person y)
{
if(x == null && y == null) return 0;
if(x == null) return ApplySortDirection(-1);
if(y == null) return ApplySortDirection(1);
switch(_columnToSortOn)
{
case "LastName":
return ApplySortDirection(SortByName(x, y));
break;
case "PostCode":
return ApplySortDirection(SortByPostCode(x, y));
break;
default:
throw new ArgumentOutOfRangeException(
string.Format("Can't sort on column {0}",
_columnToSortOn));
}
}
private int SortByPostCode(Person x, Person y)
{
return x.PostCode.CompareTo(y.PostCode);
}
private int SortByName(Person x, Person y)
{
var lastNameResult = x.LastName.CompareTo(y.LastName);
if(lastNameResult != 0)
return lastNameResult;
return x.FirstName.CompareTo(y.FirstName);
}
private int ApplySortDirection(int result)
{
return _sortAscending ? result : (result * -1);
}
}
您可以在Sort
类的AddressBook
方法中使用它,假设People
是List<Person>
:
public void Sort(bool asc, string column)
{
People.Sort(new PersonComparer(asc, column));
}
此代码具有使用就地排序的好处。
答案 2 :(得分:2)
假设:
List<Person> personList;
然后与Linq:
IEnumerable<Person> orderedByLastName = personList.OrderBy(p => p.LastName)