0

I am not the best programmer, so need some help to order this list. I had a few stabs at it, but still getting some cases which are wrong.

Essentially the list is the following:

#, ID, PreceedingID
A, 1 ,     0
B, 2 ,     3
C, 3 ,     1   
D, 4 ,     2

I want to order it so that the list follows the preceeding id. The first item will always have the preceeding ID of 0.

#, ID, PreceedingID
A, 1 ,     0
C, 3 ,     1
B, 2 ,     3   
D, 4 ,     2

Do you think you can help?

Thanks!

4

2 回答 2

4

怎么样:

var data = new[] {
    new Row{ Name = "A", ID = 1, PreceedingID = 0},
    new Row{ Name = "B", ID = 2, PreceedingID = 3},
    new Row{ Name = "C", ID = 3, PreceedingID = 1},
    new Row{ Name = "D", ID = 4, PreceedingID = 2},
};
var byLastId = data.ToDictionary(x => x.PreceedingID);

var newList = new List<Row>(data.Length);
int lastId = 0;
Row next;
while (byLastId.TryGetValue(lastId, out next))
{
    byLastId.Remove(lastId); // removal avoids infinite loops
    newList.Add(next);
    lastId = next.ID;
}

在此之后,newList将数据按所需顺序排列。

在上面,Row是:

class Row
{
    public string Name { get; set; }
    public int ID { get; set; }
    public int PreceedingID { get; set; }
}

但显然可以替代您自己的类型。

于 2013-06-20T11:29:13.010 回答
2

您可以使用例如字典对其进行排序:

Dictionary<..> d = new Dictionary<..>()
foreach(var el in list){
    d[el.PreceedingID] = el; //put data to dict by PreecedingID
}
List<..> result = new List<..>();
int prec = 0; //get first ID
for(int i = 0; i < list.Length; ++i){
    var actEl = d[prec]; //get next element
    prec = actEl.ID; //change prec id
    result.Add(actEl); //put element into result list
}
于 2013-06-20T11:28:00.103 回答