嗨,我在 c# 工作,我有两个列表如下
public class Table1
{
public long Id { get; set; }
public int mid {get;set;}
public int ChannelId { get; set; }
public string Header { get; set; }
public string FirstData { get; set; }
public string Type { get; set; }
public string SubType { get; set; }
public string Unit { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
public class Table2
{
public long Id { get; set; }
public int mid {get;set;}
public int ChannelId { get; set; }
public string DateRange { get; set; }
public string Time { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
下面是我想要的最终列表
public class FinalTable
{
public long Id { get; set; }
public int mid {get;set;}
public int ChannelId { get; set; }
public string Header { get; set; }
public string FirstData { get; set; }
public string Type { get; set; }
public string SubType { get; set; }
public string Unit { get; set; }
public List<Table2> table2List { get;set;}
}
Run Code Online (Sandbox Code Playgroud)
所以,我在Table1和 中有一些数据Table2。我正在从不同来源检索这两个列表,最后我必须以FinalTable.
在表Table1为每个mid和channelid将有相应的值Table2也。这基本上是一对多的关系,其中 foreachmid和channelidtable1 中将有多个条目Table2。
所以,最后映射后,我想以FinalTable. FinalTable 具有table2List容纳 table2 数据的属性。我可以通过编写多个或嵌套的 foreach 循环来做到这一点,但解决这个问题的最佳方法是什么。
为此,您可以使用 Linq。您的代码如下所示:
var t1 = new List<Table1>(); // your real data as a list
var t2 = new List<Table2>();
var result = t1.Select(t => new FinalTable {
Id = t.Id,
mid = t.mid,
// ...
table2List = t2.Where(x => x.mid == t.mid && x.ChannelId == t.ChannelId).ToList()
});
Run Code Online (Sandbox Code Playgroud)