[vc_custom_heading text=”Grouping”]

Is a very simple idea of taking a dataset and splitting it into several groups by a particular key.

I would like to ask you if you have ever written code like this.

public static void Main (string[] args) {
  Console.WriteLine ("Hello World!");

  List<Order> orders = new List<Order> () {
    new Order { Id = 1, Amount = 156, CustomerId = "ccalderon", Status = "Delivered" },
    new Order { Id = 14, Amount = 456, CustomerId = "sofa", Status = "Complete" },
    new Order { Id = 16, Amount = 678, CustomerId = "llrein", Status = "Pending" },
    new Order { Id = 18, Amount = 334, CustomerId = "otrvi", Status = "Complete" },
    new Order { Id = 122, Amount = 278, CustomerId = "ccalderon", Status = "Pending" },
  };

  Dictionary<string, List<Order>> result = GetOrdersByCustomer (orders);
  Dictionary<string, List<Order>> betterResult = GetBetterOrdersByCustomer (orders);
}

This method is using a dictionary to collect all the orders for a particular customer.

Basically its checking if we have not already got a list for a particular customer, then we’ll add one to the dictionary and then we add the order to the list for the customer.

Let’s try doing this better with LINQ.

public  static  Dictionary<string, List<Order>>  GetBetterOrdersByCustomer (List<Order>  orders)  {            
    return  orders.GroupBy (c  =>  c.CustomerId).ToDictionary (g  =>  g.Key,  g  =>  g.ToList ());
}

GroupBy returns IEnumerable<IGrouping<String, Order>>

Then we use the output of GroupBy into the ToDictionary extension and use the group key as the key for the dictionary and we make use of another extension method ToList to convert the content of any of this groups into a list.

LEAVE A REPLY

Please enter your comment!
Please enter your name here