Search code examples
linqentity-frameworkasp.net-mvc-4

How does "group by" work in LINQ? Error "'object' does not contain a definition for 'type'"


I just cannot understand why it works. I had this error

'object' does not contain a definition for 'type'

And it was because I was returning an anonymous type:

Connection db = new Connection();

public ActionResult Index()
{
    ViewBag.query = from input in db.field
                    where input.ID_FIELD == 1
                    select new 
                    {
                        type = input.FIELD_TYPE
                    };

    return View();
}


 @foreach (var item in ViewBag.query)
 {
     @item.type // Error here: 'object' does not contain a definition for 'type',
 }

So I added a class to get the types

public class Types
{
    public string type {get; set;}

    // And bla blab bla
}

Good, no problem. But now I need a group by clouse, but I don’t know how to do it.

For example, see the example 2 of this link. As you can see, everything works great, but here he didn’t have to specify the type, and it worked OK.

The following is my example. How can I use Group By with LINQ?


Solution

  • group x by x.PropertyName into g will result in g being a collection of x objects with a property Key that will return the x.PropertyName value that was used to group the x objects

            ViewBag.query = from input in db.field
                            where input.ID_FIELD == 1
                            group input by input.FIELD_TYPE into g
                            select new {
                                FieldType = g.Key,
                                Fields = g
                            };