在C#中使用递归获取嵌套用户
本文关键字:获取 嵌套 用户 递归 | 更新日期: 2023-09-27 18:22:11
我有一个User类,它有两个属性UserID
和ParentUserID
。这意味着用户具有自我参照关系。这是类的定义:
public class User
{
public User() { }
public User(string userid, string parentuserid)
{
this.UserID = userid;
this.ParentUserID = parentuserid;
}
public string UserID;
public string ParentUserID;
}
我需要实现一个方法,该方法应该根据UserID返回完整层次结构中存在的用户列表。我相信使用递归代码会简单得多,但我无法独自完成它。
public List<User> SubUsersHierarchy(List<User> users, string userid, int currentIndex)
{
List<User> subUsers = new List<User>();
if (currentIndex >= users.Count)
{ }
else
{
}
return users;
}
示例客户端如下:
List<User> users = new List<User>();
User user1 = new User("User2","User1");
User user2 = new User("User3", "User1");
User user3 = new User("User4", "User3");
User user4 = new User("User5", "User2");
users.Add(user1);
users.Add(user2);
users.Add(user3);
users.Add(user4);
List<User> subUsers = SubUsersHierarchy(users, "User1", 0);
上述调用的输出应为:
User2, User3, User4, User5
我能够使用以下代码实现我的目标。我想这并不太复杂。
static List<User> users = null;
static void Main(string[] args)
{
users = new List<User>();
User user1 = new User("User2","User1");
User user2 = new User("User3", "User1");
User user3 = new User("User4", "User3");
User user4 = new User("User5", "User2");
users.Add(user1);
users.Add(user2);
users.Add(user3);
users.Add(user4);
List<User> subUsersList = new List<User>();
SubUsersHierarchy("User1", subUsersList, 1, 10);
foreach (User user in subUsersList)
{
Console.WriteLine(user.UserID);
}
}
public static void SubUsersHierarchy(string userid, List<User> subUsersList, int currentLevel, int maxLevel)
{
if (currentLevel > maxLevel)
return;
List<User> subUsers = GetSubUsers(userid);
if (subUsers.Count == 0)
return;
int index = 0;
for (index = 0; index < subUsers.Count; index++)
{
User user = subUsers[index];
subUsersList.Add(user);
SubUsersHierarchy(user.UserID, subUsersList, currentLevel + 1, maxLevel);
}
}
public static List<User> GetSubUsers(string userid)
{
List<User> subusers = new List<User>();
foreach (User user in users)
{
if (user.ParentUserID == userid)
subusers.Add(user);
}
return subusers;
}
}