如何根据他们的层次排序obj?

时间:2018-04-19 10:31:48

标签: c# linq

给定2个对象PeopleRelation

public class People
{   
    public int id ;
    public string externalId;
    public PostalInfo postalInformation;
}

public class Relation
{        
    public int id ;
    public int type ;
    public string sourceExternalId ;
    public string destExternalId ;
}

People存储有关某人的信息 并Relation存储2 People之间的联系。

如何根据人们的层次排序,从“最老的”(更深的)到不太重要的人?

年龄越大,我指的是与其他元素绑定较少的元素。因此,在订购时,我可以验证并创建这些元素而不会错过参考。但是,由于验证是由人进行的,我不能等待所有这些验证一次提交它们。

var peoplesAwaitingValidation =
    new List<People> {
        new People{ id = 1 , externalId = "A" },
        new People{ id = 2 , externalId = "B" },
        new People{ id = 3 , externalId = "C" },
        new People{ id = 4 , externalId = "D" },
        new People{ id = 5 , externalId = "E" },
        new People{ id = 6 , externalId = "F" },
    };

var relationsAwaitingValidation =
    new List<Relation> {
        new Relation{ id = 1 , sourceExternalId = "A", destExternalId = "B" },
        new Relation{ id = 2 , sourceExternalId = "A", destExternalId = "C" },
        new Relation{ id = 3 , sourceExternalId = "A", destExternalId = "D" },
        new Relation{ id = 4 , sourceExternalId = "E", destExternalId = "A" },
        new Relation{ id = 3 , sourceExternalId = "E", destExternalId = "B" }
    };

//Expected result :
var orderedPeoplesAwaitingValidation = new List<People> {
                                                    // Weight
        new People{ id = 6 , externalId = "F" },    // 0 
        new People{ id = 5 , externalId = "E" },    // 1
        new People{ id = 1 , externalId = "A" },    // 2 
        new People{ id = 3 , externalId = "C" },    // 3
        new People{ id = 4 , externalId = "D" },    // 3
        new People{ id = 2 , externalId = "B" },    // 5
    };

我想到的图形表示:

1        2        3   // <==  Weight
E  --->  A  --->  B
            --->  C
            --->  D
   --->  B

F==0

mcve and attempt

1 个答案:

答案 0 :(得分:3)

你应该多次对你的关系进行迭代,以找到从我们知道权重开始的新关系。

Dictionary<string, int> weights = peoplesAwaitingValidation
    .Where(x => relationsAwaitingValidation
        .Count(o => o.destExternalId == x.externalId) == 0)
    .ToDictionary(o => o.externalId, o => 0);
int processed = 0;
while (processed < relationsAwaitingValidation.Count - 1)
    foreach (Relation r in relationsAwaitingValidation)
        if (weights.ContainsKey(r.sourceExternalId) &&
           !weights.ContainsKey(r.destExternalId))
        {
            weights.Add(r.destExternalId, weights[r.sourceExternalId] + 1);
            processed++;
        }

注意:此代码假定始终至少有一个与之无关的root用户。