将flat转换为层次结构列表?

时间:2016-10-20 10:27:37

标签: c# asp.net entity-framework entity-framework-6

我有两个表“CategoryGroup”和“Category”,它们在一个列表中返回数据。要求是将平面列表转换为层次结构列表,例如CategoryGroup包含相关类别。

Result from both the tables

请建议如何转换成hieararchy列表?

 public class ProfileConditionGroup
{
    public Guid ConditionGroupGUID { get; set; }
    public string ConditionGroupName { get; set; }
    public List<ProfileConditionList> profileConditions { get; set; }
}

public class ProfileConditionList
{
    public string ConditionName { get; set; }
    public Nullable<Guid> ConditionGUID { get; set; }
    public string[] ThisConditionSelectedByProfileIDs { get; set; }
    public Nullable<Guid> ParentConditionGroupGUID { get; set; }
    public bool IsDefaultSelected { get; set; }
}

1 个答案:

答案 0 :(得分:0)

如果没有实际的具体返回类型,这实际上有点棘手,但如果您只是构建一个Guid值的树,这就是我解决它的方式。

鉴于此查询:

var query =
    from pcg in pcgs
    from pcl in pcg.profileConditions
    select new
    {
        pcg.ConditionGroupName,
        pcg.ConditionGroupGUID,
        pcl.ConditionName,
        pcl.ConditionGUID,
        pcl.ThisConditionSelectedByProfileIDs,
        pcl.ParentConditionGroupGUID,
        pcl.IsDefaultSelected,
    };

......我会这样做:

var lookup = query.ToLookup(x => x.ParentConditionGroupGUID);

Func<Guid?, Tree<Guid?>> build = null;
build = g =>
{
    var r = new Tree<Guid?>() { Value = g };
    r.AddRange(lookup[g].Select(x => build(x.ConditionGroupGUID)));
    return r;
};

现在您只需致电build(null),您就会得到Guid?的树。如果您可以创建自己的输出类,则可以将函数更改为Func<Guid?, Tree<YourOutputClass>>

树需要这个类:

public class Tree<T> : List<Tree<T>>
{
    public T Value { get; set; }
}