.net 在C#中将平面对象列表转换为嵌套对象列表

z9ju0rcb  于 2023-05-30  发布在  .NET
关注(0)|答案(1)|浏览(110)

我对.Net和c#还很陌生,我遇到过一种情况,我必须将一个平面对象列表转换为一个嵌套对象列表。我被卡住了,不能再动了。
我有这个

[
    {
        id: 1,
        name: "abc",
        date: "8/8/20"
    },
    {
        id: 2,
        name: "xyz",
        date: "9/8/20"
    },
    {
        id: 1,
        name: "def",
        date: "9/8/20"
    }
]

我需要把它转换成这个

[
    {
        id: 1,
        nameList: [
            {
                name: "abc",
                date: "8/8/20"
            },
            {
                name: "def",
                date: "9/8/20"
            }
        ]
    },
    {
        id: 2,
        nameList: [
            {
                name: "abc",
                date: "8/8/20"
            }
        ]
    }
]

有人能帮帮我吗?

aurhwmvo

aurhwmvo1#

您可以使用Linq's GroupBy来实现这一点:

List<Record> records =...

IEnumerable<IGrouping<int, Record>> groups = records.GroupBy(r => r.id);

注意,如果你真的想要你写的输出,结果不是一个列表:

var nested = records.GroupBy(r => r.id).Select(g =>
    new
    {
       id = g.Key,
       children = g.Select(cr =>
       new 
       {
         name = cr.name,
         date = cr.date
       }).ToList()
    }).ToList());

Link to Fiddle

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    class Record
    {
        public int id {get; set;}
        public string name {get; set;}
        public DateTime date {get; set;}
    }

    public static void Main()
    {
        var records = new List<Record>()
        {
            new Record()
            {
                id = 1,
                name = "abc",
                date = new DateTime(2020, 8, 8)
            },
            new Record()
            {
                id = 2,
                name = "def",
                date = new DateTime(2020, 8, 9)
            },
            new Record()
            {
                id = 1,
                name = "def",
                date = new DateTime(2020, 8, 9)
            }
        };

        var nested = records.GroupBy(r => r.id).Select(g =>
            new
            {
               id = g.Key,
               children = g.Select(cr =>
               new 
               {
                 name = cr.name,
                 date = cr.date
               }).ToList()
            }).ToList();

        foreach (var parent in nested)
        {
            Console.WriteLine($"Parent #{parent.id}");

            foreach (var child in parent.children)
            {
                Console.WriteLine($"\tChild {child.name} {child.date}");
            }
        }
    }
}

家长#1孩子abc 8/8/2020 12:00:00 AM孩子def 8/9/2020 12:00:00 AM
家长#2儿童def 8/9/2020 12:00:00 AM

相关问题