I have two 2 tables in my database
Table: Foo Table: Bar
----------------- ---------------------
|FooID | Int| |BarID | Int |
|Number | Int| |FooID | Int |
----------------- |Name | String |
|Value | Int |
---------------------
With data with data
|FooID | Number | |BarID |FoodID |Name |Value |
|1 | 1 | |1 |1 |apple |100 |
|2 | 2 | |2 |1 |orange |110 |
|3 |2 |apple |200 |
|4 |2 |orange |40 |
These are the related models
class Foo
{
public int FooID { get; set; }
public int Number { get; set;}
public virtual ICollection<Bar> Bars { get; set; }
}
class Bar
{
public int BarID { get; set; }
public int FooID { get; set; }
public string Name { get; set;}
public int Value { get; set;}
}
I can easly display this in a table like format by doing the follwing in the view
<table>
@foreach(var f in Model)
{
<tr>
foreach(var b in f.Bar)
{
<td>@f.Number</td>
<td>@b.Name</td>
<td>@b.Value</td>
}
</tr>
}
</table>
Which outputs
-------------------
|1 |apple |100|
-------------------
|1 |orange |110|
-------------------
|2 |apple |200|
-------------------
|2 |orange | 40|
-------------------
What I’d really to see for the output is the following.
-------------------------
| | 1 | 2 |
-------------------------
|apple |100 |200 |
-------------------------
|orange |200 | 40 |
-------------------------
Can someone please point me in the right direction???
Maybe there are more elegant solutions exist, but here is how I would do it.
You need one loop to generate the header rows from
Foo.Numberthen you need a second loop where you select all theBars and group them by theirName. From these groups you can generate the data rows.Now you only need a thrid loop which goes through the
Bar.Values and builds the table row.So the above described “algorithm” in code:
Note: I’ve added the
OrderBy(b => b.FooID)to make sure that theBarvalues correctly aligned with theFoo.Numberheaders.And this how the result looks like: