Passionforprogrammingc Passionforprogrammingc - 10 days ago 5
C# Question

Pair items in a list by their type and display in the view in one loop

Model.Results


is a list object that holds list of result model.

public List<result> Results {get; set;}

class result
{
public int Id {get; set;}
public int resultId {get; set;}
public string resultName {get; set;}
public int resultTypeId {get; set;}
public string resultValue {get; set;}
}


What I need to do now is display that list in the view which is straight forward:

@foreach(var result in Model.Results)
{
<ul>
<li> @result.resultName</li>
<li> @result.resultValue</li>
</ul>
}


But what I need to do is check if the resultTypeId is the same I want to display the resultValue on the same row:

@foreach(var result in Model.Results)
{
<ul>
<li> @result.resultName</li>
@if(result.resultTypeId == any other result.resultTypeId in the list)
{
<li> @result.resultValue - @the other result.resultValue</li>
}
@else
{
<li> @result.resultValue</li>
}
</ul>
}


Please let me know if you need me to illustrate more. When I look at the logic it looks straight forward but when I start coding I can't see a way round it.

Thanks in advance.

Answer

You can group your items by the ID:

 @foreach(var resultGroup in Model.Results.GroupBy(result => result.resultTypeId))
 {
     <ul>
     <li> @resultGroup.First().resultName</li>
     @foreach (var result in resultGroup) {
        <li> @result.resultValue</li>
     }
     </ul>
 }
Comments