本例中获取的是所有的晚辈!首先定义家庭成员类:

    public class FamilyMember
    {
        /// <summary>
        /// 身份
        /// </summary>
        public string identity { get; set; }
        public int level { get; set; }
        /// <summary>
        /// 父亲
        /// </summary>
        public string father { get; set; }
    }

然后,定义递归方法:

        /// <summary>
        /// 递归获取晚辈
        /// </summary>
        /// <param name="members"></param>
        /// <param name="m"></param>
        /// <returns></returns>
        public static List<FamilyMember> GetYoungers(List<FamilyMember> members, FamilyMember m)
        {
            var result = new List<FamilyMember>();

            //获取该员工的直属下级
            var subordinate = members.Where(e => e.father == m.identity).ToList();

            //如果存在直属下级
            if (subordinate != null)
            {
                result.AddRange(subordinate);
                foreach (var subo in subordinate)
                {
                    result.AddRange(GetYoungers(members, subo));
                }
            }

            return result;
        }

  方法解释:

    首先,既然是递归,肯定是自己调用自己;

    然后,在方法体内部:

        既然要获取所有的下属(晚辈),首先要获取自己的直属下属,并将结果存入“下属”集合中;

        然后通过递归,获取 “直属下属的直属下属”,同样存入“下属”集合中;

        最后,返回“下属”集合。

递归测试:

        /// <summary>
        /// 测试递归
        /// </summary>
        public static void CheckRecursion()
        {
            List<FamilyMember> list = new List<FamilyMember>
            {
                new FamilyMember{ identity = "爷爷", level = 1, father = ""},
                new FamilyMember{ identity = "爸爸", level = 2, father = "爷爷"},
                new FamilyMember{ identity = "叔叔", level = 2, father = "爷爷"},
                new FamilyMember{ identity = "自己", level = 3, father = "爸爸"},
                new FamilyMember{ identity = "弟弟", level = 3, father = "爸爸"},
                new FamilyMember{ identity = "堂兄", level = 3, father = "叔叔"},
                new FamilyMember{ identity = "堂弟", level = 3, father = "叔叔"},
                new FamilyMember{ identity = "儿子", level = 4, father = "自己"},
                new FamilyMember{ identity = "女儿", level = 4, father = "自己"},
                new FamilyMember{ identity = "侄子", level = 4, father = "弟弟"},
                new FamilyMember{ identity = "侄女", level = 4, father = "弟弟"}
            };

            var self = new FamilyMember { identity = "爷爷", level = 1, father = "" };

            var youngers = GetYoungers(list, self).OrderBy(p => p.level).ToList();
            if(youngers != null)
            {
                foreach(var p in youngers)
                {
                    Console.WriteLine(p.identity);
                }
            }
        }

  调用该方法即可查看效果:

  

01-26 19:42