0

I´m writing an ASP .NET MVC web site and i´m with a LINQ problem. I have a simple class

public class Tag
{
    public int TagId { get; set; }
    public string Nome { get; set; }
    ... [other props]....

}

And i want to pass to the view a list of grouped Nomes. I tried to the following LINQ code to generate a list

var teste = (from t in db.Tags
                    group t by t.Nome into g
                    select new
                    {
                        Nome = g.Key
                    }).ToList();
ViewBag.ListaTags = teste;

and it´s ok, but if i use the following code in the View

@foreach (var item in ViewBag.ListaTags)
{
     @item.Nome
}

I got an error message saying that the object item has no Nome property. If i try @item instead of @item.Nome, it display {Nome = "Test"}. It´s like I have an object but I can´t access it´s properties.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150

2 Answers2

0

After Grouping you are having structure of Grouped data in format like::

Group.key1=> [value1,value2,value3],
Group.key2=> [value1,value2,value3],
Group.key3=> [value1,value2,value3]

And if you want to show something grouped then you should select Grouped values also with its Key as::

var teste = (from t in db.Tags
                    group t by t.Nome into g
                    select new
                    {
                        Nome = g.Key,
                        Id=g
                    }).ToList();

Then you can show it on client side as::

@foreach (var item in ViewBag.ListaTags)
{
    <p>@item.Key  </p>
    foreach (var subitem in item.Values)
    {
        @subitem    
    }

}
Rahul
  • 2,309
  • 6
  • 33
  • 60
0

Please have a look this Marc's answer. Instead of returning a anonymous type, you can decalre a POCO class and return that object like this:-

var teste = (from t in db.Tags
                         group t by t.Nome into g
                         select new Nome
                         {
                             groupedNome = g.Key
                         }).ToList();

POCO class I have used here is:-

public class Nome
{
     public string groupedNome { get; set; }
}

Then , you can use this in View as:-

@foreach (var item in ViewBag.ListaTags)
{
     @item.groupedNome
}
Community
  • 1
  • 1
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56