【问题标题】:Best way to map a parent-child list of objects映射对象的父子列表的最佳方法
【发布时间】:2018-08-03 21:57:52
【问题描述】:

在这里使用 C#。我有一个包含 3 个属性的遗留类 Person:

  1. ID(指导)
  2. 姓名
  3. 父 ID (guid)

在 SQL 中,它存储在两个表中:

  1. 表人:包含 ID 和姓名
  2. 表关系:包含 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 是一个包含以下内容的类:

  • 身份证
  • 姓名
  • 儿童为List<NewPerson>

以树的形式显示它们:

  • 鲍勃
  • --- 斯科特
  • -------- 小斯科特
  • -------- 约翰
  • 詹姆斯
  • --- 小詹姆斯

有没有一种有效的方法将旧单位 List<Person> 映射到分层(世代)List<NewPerson>

【问题讨论】:

  • 在数据库中执行此操作的传统方法是在名为 ParentId 的 person 表中添加第三个(可为空的)列。这样,您就不需要“关系”表。然后为了获得整个层次结构,您执行“自连接”(或“递归自连接”)(搜索的好关键字)。你使用的是什么 ORM(EF、Linq2Sql、Dapper、...)?

标签: c# linq


【解决方案1】:

我为这个问题写了一个Test,之前注意哪个数据是从哪里来的?数据库?还是它们在记忆中??

我写了这两种状态。

  1. 来自数据库的数据代码:

        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()
        });
    
  2. 内存中数据的代码:

        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; }
}

这些代码用于多级数据。

祝你好运。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    相关资源
    最近更新 更多