So I have a List<SearchResult> Results that will return multiple results for a single Category property, when the Item property is different.
So for example the results could be:
SearchResult[0].Category = "Food"
SearchResult[0].Item = "Ham"
SearchResult[1].Category = "Food"
SearchResult[1].Item = "Cheese"
SearchResult[2].Category = "Food"
SearchResult[2].Item = "Crackers"
SearchResult[3].Category = "Drink"
SearchResult[3].Category = "Juice"
etc.
Now I want to display them like this:
Items in the Food category include: Ham, Cheese, and Crackers
Items in the Drink category include: Drink
etc.
But this is what I have now:
@foreach (SearchResult result in Results)
{
<p>Items in the @result.Category category include: @result.Item </p>
}
Which of course is displaying the data like this:
Items in the Food category include: Ham
Items in the Food category include: Cheese
Items in the Food category include: Crackers
Items in the Drink category include: Juice
Now I feel like there must be some LINQ magic I can work on that List and do this properly, rather than manually coding a loop that separates them off into individual lists.
What’s the trick?
The trick is using the group clause / the GroupBy Method.
and