如何在C#中创建父子关系列表?

时间:2014-12-18 10:35:40

标签: c#

我有以下课程:

public class Parent
{
    private int Id;
    private String Title;
    private int? Parent;
}

以下对象:

id:1,title:"Europe",parent:null  
id:2,title:"Western Europe",parent:1  
id:3,title:"Eastern Europe",parent:1  
id:5,title:"Germany",parent:2 

我想通过ID

创建标题字符串
  

getallparent(5)将返回Europe,Western Europegetparent(3)将返回Europe

我如何在C#中做到这一点?

这是一个国家/地区列表:所有国家/地区都有ID,标题和父母 id 1是没有父母的欧洲,id 3是西欧,父母1,id 5是德国,父母3 所以我想给一个id,

  

in my example 5, which should return Europe, Western Europe

1 个答案:

答案 0 :(得分:1)

如果包含所有已创建的Parent对象的集合,则可以使用此列表搜索符合所需条件的列表,并编译符合要求的子集。然后可以使用它来格式化您需要的输出字符串。

    public class Parent
{
    private int Id;
    private String Title;
    private int? Parent;

    // Private static fields for managing Ids and the list of all instances
    private static List<Parent> _allParents = new List<Parent>();
    private static int _nextId = 0;

    // Default constructor
    public Parent()
    {
        // Set default field values.
        this.Id = _nextId++;
        this.Title = "";
        this.Parent = null;

        // Store the new object in the static collection.
        _allParents.Add(this);
    }

    /// <summary>
    /// Constructs a list of Parent objects whose Ids have corresponding Parent objects.
    /// NOTE: This method returns a List that includes the Parent object with the Id
    /// passed in.  This will be the first item in the List and should be skipped if
    /// only higher level relationships are required.
    /// </summary>
    /// <param name="Id">Nullable<int> Id of the item whose parents are to be found.</param>
    /// <returns>List<Parent> of the Parents objects</returns>
    public List<Parent> ListParents(int? Id)
    {
        List<Parent> parents = new List<Parent>();
        // Id values that are null mark the end of the ancestor chain
        while (Id.HasValue)
        {
            // Find the Parent with the requested Id
            var parent = _allParents.Find(p => { return this.Id == p.Id; });
            // null means no Parent object with the requested Id exists
            if (null != parent)
            {
                // Add the Parent and its parents.
                parents.Add(parent);
                // Check for the next Id
                Id = parent.Id;
            }
        }
        return parents;
    }

    public String GetAllParents(int? Id)
    {
        StringBuilder allParents = new StringBuilder();

        // Find all the parents
        List<Parent> parents = ListParents(Id);

        // Add the Title of each parent in the list to the result
        for(int n = 0; n < parents.Count; n++)
        {
            allParents.Append(parents[n].Title);

            // Seperate all but the last parent with commas
            if(n < (parents.Count - 1))
                allParents.Append(", ");
        }

        return allParents.ToString();
    }
}

正如一些评论中所指出的,使用关系数据库样式ID会使此实现比必要的更复杂。使用对现有对象的引用替换它,创建标准链接列表可以简化解决方案。