【问题标题】:How to Map Lists in c#?如何在 C# 中映射列表?
【发布时间】:2021-07-27 13:24:23
【问题描述】:

您好,我在 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; } 
}
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; }
}

下面是我想要的最终列表

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;}
}

所以,我在Table1Table2 中有一些数据。我正在从不同的来源检索这两个列表,最后我必须以FinalTable 的形式准备列表。

在表Table1 中,midchannelid 中的每个Table2 也会有相应的值。这基本上是一对多的关系,其中 foreach midchannelid 在 table1 中将有多个条目在 Table2

所以,最后映射后我想以FinalTable 的形式显示数据。 FinalTable 具有属性table2List 来容纳table2 数据。我可以通过编写多个或嵌套的 foreach 循环来做到这一点,但解决这个问题的最佳方法是什么。

【问题讨论】:

  • 你试过什么?你在哪里卡住?你看过LINQ吗?

标签: c# .net list


【解决方案1】:

您可以为此使用 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()
});

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 2011-12-04
    • 2021-09-27
    • 2016-04-16
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 2014-09-10
    相关资源
    最近更新 更多