CallumVass
CallumVass

Reputation: 11448

ASP.NET MVC - Return a List, grouped by a property in my Model

How do I return a List, grouped by a property?

In my action, I return a view like so:

return View(context.Lines.Where(x=>x.EnquiryId == id).ToList());

This works fine, but what I need to do is group these Lines by a particular vehicle. In my Lines table, this has a column which stores the vehicle ID that a particular Line is linked too. For example, line 1 and 2, may have a vehicle ID of 1, where as line 3 and 4 may have a vehicle ID of 2.

Upvotes: 0

Views: 1875

Answers (1)

Roy Dictus
Roy Dictus

Reputation: 33139

Do you want to group or just order? Because if your result is a list of items, you'll just want to order them properly.

var result = context.Lines
    .Where(x => x.EnquiryId == id)
    .OrderBy(x => x.VehicleId)
    .ToList();

GroupBy returns a list of lists:

var result = context.Lines
    .Where(x => x.EnquiryId == id)
    .GroupBy(x => x.VehicleId);

Upvotes: 2

Related Questions