【问题标题】:How to sort DB records by parent [closed]如何按父级对数据库记录进行排序[关闭]
【发布时间】:2018-01-25 22:48:27
【问题描述】:

我有这样的数据库表:

ID    Name    ParentID    isActive
1      ABC   NULL         true
2      DEF   1            true
3      GHI   1            true
4      JKL   NULL         true
5      MNO   4            true
6      PRS   NULL         true
7      TUV   NULL         true
8      WX    1            true
9      YZ    4            true
10     abc   7            true

我把它列在清单上:

var projectList = connection.Where(d=>d.Active);

当我将此表添加到列表时,我想按父 ID 对它们进行排序。所以,排序后的列表应该是这样的:(每一行都替换了它的父行)。

  • 1 是 2,3 和 8 的父级

  • 4 是 5 和 9 的父级

1|ABC
2|DEF
3|GHI
**4|WX**
5|JKL
6|MNO
**7|YZ**
8|PRS
9|TUV
**10|abc**

如何对这个列表进行排序?

【问题讨论】:

  • 你想用 linq 还是 sql 排序?
  • 您需要在列表中使用 OrderBy 方法。 msdn.microsoft.com/en-us/library/bb534966(v=vs.110).aspx
  • 也许...order by ID
  • 我使用 Linq。你有答案吗? (父母->孩子,其他父母->这是孩子)。所以我想在父行之后列出子行。

标签: c# sql asp.net linq sorting


【解决方案1】:

您只需通过区分父元素和子元素将结果与自身连接。我希望它有所帮助。

static void Main(string[] args)
{
  var connection = new List<User>()
  {
    new User(1, "ABC", null, true),
    new User(2, "DEF", 1, true),
    new User(3, "GHI", 1, true),
    new User(4, "JKL", null, true),
    new User(5, "MNO", 4, true),
    new User(6, "PRS", null, true),
    new User(7, "TUV", null, true),
    new User(8, "WX", 1, true),
    new User(9, "YZ", 4, true),
    new User(10, "abc", 7, true)
  };


  var filtered = connection.Where(x => x.Active).OrderBy(z => z.ParentID);
  var result = filtered.Where(p => p.ParentID == null).GroupJoin(filtered, parent => parent.ID,
      child => child.ParentID,
      (parent, child) => new {Child = child, Parent = parent})
    .Aggregate(new List<User>(), (outList, tempObj) =>
    {
      outList.Add(tempObj.Parent);
      outList.AddRange(tempObj.Child);       
      return outList;
    });

  foreach (var item in result)
  {
    Console.WriteLine($"{item.ID} | {item.Name} | {item.ParentID}");
  }
}

它产生以下输出:

1 | ABC | 2 | DEF | 1 3 | GHI | 1 8 | WX | 1 4 | JKL | 5 | MNO | 4 9 | YZ | 4 6 | PRS | 7 | TUV | 10 | abc | 7

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2014-01-12
    相关资源
    最近更新 更多