Click here to Skip to main content
16,022,131 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi everyone, I am trying to dispay products by thier categories using foreach loop. But my code still displaying duplicate categories.
I want to display Category heading then the products related to that category and so on.

The problem is, I am getting dulipcate categories.

Please help, thanks in advance

What I have tried:

@{
    var category= Model.Select(x=>x.Category).Distinct().ToList();
}

@foreach(var products in Model)
{
    @for(int i=0; i<category.Count; i++)
    {

     if (products.category== category[i])
     {
        <p>@products .category</p>
     }

     if (products.Category != category[i])
     {
       <p>text</p>
     }

    }
}
Posted
Updated 14-Sep-24 7:09am
v2
Comments
Dave Kreskowiak 14-Sep-24 11:14am    
OK, and the problem is?
Hania Anum 14-Sep-24 17:06pm    
I want to display Category heading then the products related to that category and so on.
The problem is, I am getting dulipcate categories.

Could I suggest that you use the Linq GroupBy method? Something along these lines. I have assumed that the Product class has a Name property.


@{
     var groups = Model.GroupBy(
     m => m.Category, //key 
     m => m.Product,//collection 'group'
     (key, g) => new { Category = key, Products= g });
}

@foreach (var group in groups)
   {
     <h2>@group.Category</h2>
     @foreach (var product in group.Products)
     {
      <p>@product.Name</p>
     }    
   }
 
Share this answer
 
Your code is displaying duplicate categories, probably because it's matching multiple entries in the category array. You have have duplicates in that array.

Also, if you a second IF statement you don't need at all. This can be removed:
C#
if (products.Category != category[i])
{
    <p>text</p>
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900