Friday, December 28, 2012

Tips: Sorting/Ordering a Collection with Nested/Child Collection value

 

Problem:

Suppose you have a collection and inside that collection you have a child collection. Here is a example of such relation

   1: public class Vahicle
   2:     {
   3:         public int VahicleId { get; set; }
   4:         public string ValicleName { get; set; }
   5:         public List<Reminder> Reminders { get; set; }
   6:     }
   7:  
   8:     public class Reminder
   9:     {
  10:         public int ReminderId { get; set; }
  11:         public string ReminderType { get; set; }
  12:     }

Here you can see Reminder is a nested collection inside Vahicle. You can have  a collection of Vahicles and you may want to display Vahicles shorting by ReminderType.


 


Solution:


To solve this problem I have converted the collection to flat list where there have a property ReminderType so that when I do order by using ReminderType. The total collection will be sorted. SelectMany convert nested collection to flat collection. So I used SelectMany(). to make a flat collection with ReminderType.



   1: var orderedVahicles = vahicles.SelectMany(v => v.Reminders
   2:                                                           .Select(reminder => new { Vahicle = v, reminder.ReminderType })
   3:                                                      ).OrderBy(v => v.ReminderType)
   4:                                                      .Select(v => v.Vahicle).Distinct();

Here is the code Line 1-2 I converted Vahicle nested Collection into a collection where Vahicle collection is a property and also ReminderType is a property using SelectMany(). After Converting the collection I have done orderby with ReminderType and vahicle is also sorted Line 3. As I only need sorted Vahicle collection so I selected only Vahicle property from anonymous object Line 4.


Problem could be more complex  where you may need to select object based on certain criteria and also collection can be nested 3-4 levels or more. You can do another SelectMany if there have another nested collection.

1 comment:

  1. Harrah's Cherokee Casino & Hotel - Mapyro
    This smoke-free casino resort features an outdoor 동두천 출장샵 pool and 청주 출장샵 comfortable 광주 출장샵 rooms. Casino guests 아산 출장안마 can enjoy nightly entertainment with family and friends. Rating: 7/10 · ‎924 reviews 사천 출장샵

    ReplyDelete