Search code examples
c#linqmodel-view-controllernorthwind

How to group Northwind orders based on Customer ContactName


I am new to C# and LINQ and I am using Northwind database. My view displays all orders from the database without ordering. I want to display orders based on contact name (customer) and alphabetically: for example, AVARIA and under it all orders of this customer. And so on...

I want something like this:

AVARIA

ORDER 1 OF AVARIA FROM DATABASE WITH ITS DETAILS 
ORDER 2 OF AVARIA FROM DATABASE WITH ITS DETAILS  
ORDER 3 OF AVARIA FROM DATABASE WITH ITS DETAILS  

BECUA

ORDER 1 OF BECUA FROM DATABASE WITH ITS DETAILS
ORDER 2 OF BECUA FROM DATABASE WITH ITS DETAILS  

and so on... 

Because this is showing me all the orders coming from the database without any ordering, like customer X in the first row with an order, then customer Y, then again customer X with another order, and so on. I tried this:

public ActionResult Index()
{
    var orders = db.Orders.Include(o => o.Customer).Include(o => o.Employee).Include(o => o.Shipper);
    var list = orders.OrderBy(x => x.Customer.ContactName);

    return View(list.ToList());
}

But it raised the following exception:

An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

The view works fine.

Please help.


Solution

  • you can use group by and orderby. sample:

    class Program
    {
    
        class grpitem
        {
            public string groupCode;
            public string item;
        }
    
        static List<grpitem> list = new List<grpitem>()
        {
             new grpitem() {groupCode="3", item="b"},
             new grpitem() {groupCode="1", item="b"},
             new grpitem() {groupCode="3", item="c"},
             new grpitem() {groupCode="2", item="b"},
             new grpitem() {groupCode="2", item="a"},
             new grpitem() {groupCode="2", item="c"},
             new grpitem() {groupCode="1", item="a"},
             new grpitem() {groupCode="3", item="a"},
             new grpitem() {groupCode="3", item="d"}
        };
    
        static void Main(string[] args)
        {
            IEnumerable<grpitem> ordered = list.GroupBy(grp => grp.groupCode)
                .SelectMany(g => g.OrderBy(grp => grp.item)).OrderBy(g => g.groupCode);
    
            foreach(grpitem g in ordered)
                Console.WriteLine("groupCode:{0} item:{1}",g.groupCode,g.item);
    
            Console.ReadLine();
        }
    }
    

    Output:

    groupCode:1 item:a
    groupCode:1 item:b
    groupCode:1 item:c
    groupCode:1 item:d
    groupCode:2 item:a
    groupCode:2 item:b
    groupCode:3 item:a
    groupCode:3 item:b
    groupCode:3 item:c