使用您的原始类定义,我组合了一个小型、可运行的 ASP.NET Core 控制台应用程序(请参见下面的代码)。
从Data 对象到Info 对象的转换发生在作为infoList.AddRange(...); 参数的LINQ 查询中。
GetData() 是一个本地函数,它只构建一个IList<Data>,其中包含几个Data 对象,每个对象都带有一个嵌入的IList<Weight> 集合。结果应该类似于代码中des 对象的内容。
注意.SelectMany() 查询GetData() 返回的IList<Data> 并返回一个IEnumerable<>,其中包含调用它的集合中每个对象的一个或多个对象。请注意.Select() 和.SelectMany() 的不同之处在于.Select() 只为原始集合中的每个对象生成一个输出对象,而.SelectMany() 可以为每个输入对象返回多个输出对象。
.SelectMany() 的参数是一个 lambda,d => d.Weight.Select(w => ...)。这很重要,因为Data 类包含一个collection(即IList<Weight>)Weight 对象。这使我们可以访问d 参数中的Data 对象和w 参数中的每个权重对象(一次一个)。
最后,.Select(...) 为每个 Weight 对象返回一个新的 Info 对象,其中包含代码中显示的属性值。
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqReformatObject
{
class Program
{
static void Main(string[] args)
{
var infoList = new List<Info>();
infoList.AddRange(
GetData()
.SelectMany(d =>
d.Weight
.Select(w =>
new Info
{
title = d.title,
weight = w.weight,
Date = w.Date
}
)
)
);
foreach (var i in infoList)
{
Console.Write($"\"title\": \"{i.title}\", ");
Console.Write($"\"date\": \"{i.Date.ToString("O")}\",");
Console.Write($"\"weight\": \"{i.weight}\"");
Console.WriteLine();
}
}
public class Data
{
public string title { get; set; }
public List<Weight> Weight { get; set; }
}
public class Weight
{
public DateTime Date { get; set; }
public string weight { get; set; }
}
public class Info
{
public string title { get; set; }
public string weight { get; set; }
public DateTime Date { get; set; }
}
static IList<Data> GetData()
{
return new List<Data>()
{
new Data() {
title = "Paul's weight log",
Weight = new List<Weight>() {
new Weight () {
Date = DateTime.Parse("2017-04-21T00:00:00Z"),
weight = "120kg"
},
new Weight () {
Date = DateTime.Parse("2017-09-15T00:00:00Z"),
weight = "125kg"
},
new Weight () {
Date = DateTime.Parse("2017-10-27T00:00:00Z"),
weight = "130kg"
}
}
},
new Data() {
title = "John's weight log",
Weight = new List<Weight>() {
new Weight () {
Date = DateTime.Parse("2017-06-21T00:00:00Z"),
weight = "101kg"
},
new Weight () {
Date = DateTime.Parse("2017-08-15T00:00:00Z"),
weight = "98kg"
},
new Weight () {
Date = DateTime.Parse("2017-11-27T00:00:00Z"),
weight = "94kg"
}
}
},
new Data() {
title = "Ringo's weight log",
Weight = new List<Weight>() {
new Weight () {
Date = DateTime.Parse("2017-03-21T00:00:00Z"),
weight = "98kg"
},
new Weight () {
Date = DateTime.Parse("2017-06-15T00:00:00Z"),
weight = "100kg"
},
new Weight () {
Date = DateTime.Parse("2017-09-27T00:00:00Z"),
weight = "102kg"
}
}
},
new Data() {
title = "George's weight log",
Weight = new List<Weight>() {
new Weight () {
Date = DateTime.Parse("2017-01-21T00:00:00Z"),
weight = "99kg"
},
new Weight () {
Date = DateTime.Parse("2017-03-15T00:00:00Z"),
weight = "103kg"
},
new Weight () {
Date = DateTime.Parse("2017-05-17T00:00:00Z"),
weight = "113kg"
},
new Weight () {
Date = DateTime.Parse("2017-07-19T00:00:00Z"),
weight = "111kg"
},
new Weight () {
Date = DateTime.Parse("2017-09-23T00:00:00Z"),
weight = "109kg"
}
}
}
};
}
}
}