在此使用C#。我有一个遗留类Person,它包含3个属性:
- Id(guid(
- 名称
- 父Id(guid(
在SQL中,它存储在两个表中:
- 表人员:包含Id和Name
- 表关系:包含PersonId、ParentId
例如,给定的Person对象(为了简单起见,不显示guid(:
- parent1:Id=1,Name=Bob,ParentId=空
- child1:Id=2,Name=Scott,ParentId=1
- child11:Id=3,Name=Scott jr,ParentId=2
- child12:Id=4,Name=John,ParentId=2
- parent2:Id=5,Name=James,ParentId=空
- child21:Id=6,Name=James jr,ParentId=5
我想构建List<NewPerson>
其中NewPerson
是包含的类
- Id
- 名称
- 儿童作为
List<NewPerson>
以树状形式显示它们:
- Bob
- ---斯科特
- --------小斯科特
- --------约翰
- 詹姆斯
- ---小詹姆斯
有没有一种有效的方法将旧的平面List<Person>
映射到分层(代(List<NewPerson>
?
我为这个问题写了一个测试,在关注之前,数据来自哪里?数据库或者它们在记忆中??
我写这两种状态。
-
来自数据库的数据代码:
listPerson.GroupBy(x => x.ParentId).Select(x => new TreePerson() { Id = x.First(c=>c.ParentdId == x.Key).Id, Name = x.First(c => c.ParentId == x.Key).Name, Children = x.Where(c => c.ParentdId == x.Key).GroupBy(c => c.Id).Select(c => new Person() { Id = c.Key, Name = c.First(z => z.Id == c.Key).Name, SubLevelPerson = c.FirstOrDefault(v=>v.ParentdId == c.Key) }).ToList() });
-
内存中数据的代码:
listPerson.Where(x => x.ParentdId == null).Select(x => new TreePerson() { Id = x.Id, Name = x.Name, Children = listPerson.Where(c => c.ParentdId == x.Id).GroupBy(c => c.Id).Select(c => new Person() { Id = c.Key, Name = c.First(z => z.Id == c.Key).Name, SubLevelPerson = c.FirstOrDefault(v => v.ParentdId == c.Key) }).ToList() });
注意你的类应该喜欢这样的类:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentdId { get; set; }
public Person SubLevelPerson { get; set; }
}
public class TreePerson
{
public int Id { get; set; }
public string Name { get; set; }
public List<Person> Children { get; set; }
}
这些代码用于多级数据。
好运。