0

I'm trying to group by CategoryId and display the CategoryId + the Name property of the group, I need help modifying this code so the Name property can be displayed, check out view below th see what I mean.

Database

ItemCategory
int ItemId
int CategoryId

Category
int CategoryId
int? ParentId
string Name

var itemcategories = db.Fetch<ItemCategory, Category>(@"SELECT * FROM ItemCategory LEFT JOIN Category on Category.CategoryId = ItemCategory.CategoryId WHERE ItemId = @0", item.ItemId);


var grouped = from b in itemcategories
               where b.Category.ParentId != null
               group b by b.Category.ParentId ?? 0 into g
               select new Group<int, ItemCategory> { Key = g.Key, Values = g };

public class Group<K,T>
{
    public K Key;
    public IEnumerable<T> Values;
}

In view

@foreach (var group in @Model.ItemCategories)
{
  @group.Key **Category.Name should be displayed here**
}
foreach (var value in group.Values)
{
   @value.Category.Name
}
David Lenn
  • 175
  • 1
  • 8
  • Can you be more precise what's the issue ? You already have `@value.Category.Name`. Is the problem the fact that you expect `@group.Key` to be the name of the category ? – Matt Ko Nov 02 '14 at 17:37
  • Yes, I want @group.key to be the name of the category. – David Lenn Nov 02 '14 at 17:58
  • but that's not possible with the way that you designed your Group class, because the type of `Key` is `int` and the type of `Category.Name` is `string`. So how do we do this ? – Matt Ko Nov 02 '14 at 18:12
  • I have tried adding a new property to the group class, but I didn't have any success assigning the Category.Name to that property. – David Lenn Nov 02 '14 at 18:27

1 Answers1

0

I think you're looking for the answer provided here: Group by in LINQ.
However, you should also change your DB query so that it returns the actual result of the join and not just an IEnumerable<ItemCategory>.
The Group class could look like:

public class Group<K,T>
{
    public K Key;
    public IEnumerable<T> Values;
    public IEnumerable<string> CategoryNames;
}

Note that if you want to group by ParentId, your key will always be ParentId, it's the idea of the GroupBy function.
With that new Group class and DB query, you should be able to use g.Name as the parameter for CategoryNames.

Community
  • 1
  • 1
Matt Ko
  • 969
  • 7
  • 14