给定一个一维list 将其转换成嵌套list 结构如下:
[
{
id: 1,
name: "abc",
date: "8/8/20"
},
{
id: 2,
name: "xyz",
date: "9/8/20"
},
{
id: 1,
name: "def",
date: "9/8/20"
}
]
这道题目非常好,很好的解释了如何灵活运用 Linq,我相信有很多做过报表业务的同学深有体会,经常需要将一坨数据进行 升维 或 降维,前者必用:GroupBy()
, Dictionary()
,ToLookup()
等方法,后者必用 SelectMany()
。
既然是按照 id 进行分组,业务开发中,我更多的会将其转为 Dictionary 结构,这样查找 id 就是 O(1) 的时间复杂度,完整代码如下(仅供参考
):
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
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 query = records.GroupBy(g => g.id).ToDictionary(k => k.Key, v => v.Select(m => new
{
name = m.name,
date = m.date
}).ToList());
var json = JsonConvert.SerializeObject(query, Formatting.Indented);
Console.WriteLine(json);
}
}
public class Record
{
public int id { get; set; }
public string name { get; set; }
public DateTime date { get; set; }
}
}
.net Core 中需要用NuGet 安装 引入Newtonsoft.Json
库