首页 > 解决方案 > 映射对象的父子列表的最佳方法

问题描述

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

  1. 标识(指导)
  2. 姓名
  3. 家长 ID(指导)

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

  1. 表人:包含 Id 和 Name
  2. 表关系:包含 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>

标签: c#linq

解决方案


我为这个问题写了一个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; }
}

这些代码用于多级数据。

祝你好运。


推荐阅读