c# - 映射对象的父子列表的最佳方法
问题描述
在这里使用 C#。我有一个包含 3 个属性的遗留类 Person:
- 标识(指导)
- 姓名
- 家长 ID(指导)
在 SQL 中,它存储在两个表中:
- 表人:包含 Id 和 Name
- 表关系:包含 PersonId、ParentId
例如,给定 Person 对象(为简单起见,未显示 guid):
- parent1:Id = 1,Name = Bob,ParentId = 空
- child1:Id = 2,名称 = Scott,ParentId = 1
- child11:Id = 3,名称 = Scott jr,ParentId = 2
- child12:Id = 4,名称 = John,ParentId = 2
- parent2:Id = 5,Name = James,ParentId = 空
- child21:Id = 6,名称 = James jr,ParentId = 5
我想建立List<NewPerson>
一个NewPerson
包含以下内容的类:
- ID
- 姓名
- 儿童作为
List<NewPerson>
以树的形式显示它们:
- 鲍勃
- --- 斯科特
- -------- 小斯科特
- - - - - 约翰
- 詹姆士
- --- 小詹姆斯
有没有一种有效的方法将旧公寓映射List<Person>
到分层(世代)List<NewPerson>
?
解决方案
我为这个问题写了一个Test,之前注意哪个数据是从哪里来的?数据库?或者他们在记忆中?
我写了这两种状态。
来自数据库的数据代码:
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; }
}
这些代码用于多级数据。
祝你好运。
推荐阅读
- c - 可以硬编码地址并手动将其分配给指针吗?
- firebase - Flutter Firebase 手机验证在发布到 Play 商店后不起作用
- node.js - Heroku 上部署的应用程序在启动时崩溃
- java - 如何将包添加到 Eclipse 覆盖“分析范围”部分?
- vue.js - TypeError: (0 , _testUtils.createLocalVue) 不是函数
- python - 对于频道名称 discord.py,将空格替换为“-”
- python - 构造函数和 Pydantic
- python - 熊猫,如何计算不同行中一个单元格和另一个单元格之间的增量
- c++ - 读取文件时如何从字符串中删除不必要的新行?
- r - 计算给定时期的回报 - R