我需要按层次结构对列表进行排序,有人可以帮我一把吗?名单如下:按层次结构排序列表
// create your list
List<Person> persons = new List<Person>();
// populate it
persons.Add(new Person("child", "father"));
persons.Add(new Person("father", "grandfather"));
persons.Add(new Person("grandfather", "grandgrandfather"));
persons.Add(new Person("grandgrandfather", null));
我想是这样的:
- grandgrandfather
- 爷爷
- 父亲
- 孩子
我tryed来实现IComparable在我的类“人”中,像这样:
public class Person : IComparable<Person>
{
public String ID { get; set; }
public String ParentID { get; set; }
public Person(String id, String pid)
{
this.ID = id;
this.ParentID = pid;
}
public Int32 CompareTo(Person right)
{
if (this.ID.Equals(right.ID))
return 0;
if (this.ParentID == null) return -1;
if (right.ParentID == null) return 1;
return this.ParentID.CompareTo(right.ID);
}
}
但没有做的事...
您无法实现IComparable,因为您必须知道集合中的其他项目才能比较它们。你有什么机会让你的人类拥有一个int generation属性,并说他们是第一代,第二代或第三代? – Daryl
你需要一个拓扑排序,就像http://stackoverflow.com/questions/7788364/building-ordering-a-tree-as-a-list-in-c-sharp/7789273#7789273。我们需要更多关于您的实际问题的细节才能够提供更多帮助。 – Gabe