Hi I am working in c# and I have two list as below
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; }
}
Below is the final List I want
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;}
}
So, I have some data in Table1 and Table2. I am retrieving these two lists from different sources and finally I have to prepare list in the form of FinalTable.
In table Table1 for each mid and channelid there will be corresponding values in Table2 also. This is basically one to many relationship where foreach mid and channelid in table1 there will be multiple entries in Table2.
So, after mapping finally I would like to show data in the form of FinalTable. FinalTable has property table2List to accomodate table2 data. I can do this by writing multiple or nested foreach loops but what would be the best approach to solve this.
You can use Linq for this. Your code would look like:
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()
});