Monday, December 19, 2016

Generic List - Inserting item in the proper order

Happy Whatever Holiday You Are Or Soon Will Be Celebrating!  Christmas for me!

Recently I had a requirement to insert a new item in a generic list in the proper order according to two properties in the collection object.  The solution I came up with, with the help of some Googling, is:
  1. From the item to be inserted, combine its values for the two properties into a single string.
  2. Sort the list of generic list of objects in descending order by the the first property, and then the second.
  3. Find the index of the first item whose combined property values are less than the combined values of the item to be inserted.  Add 1 to the index to insert the new item in the next "slot".
  4. If there are no items with a lesser combined value return 0.  I.E. insert the new item first in the list.
Below is a C# method that uses the steps above to return an integer representing the index to insert a new item in to a list according to two property values:
 public static int CalculateInsertIndex(List<ObjectName> listOfObjects, string propertyValue1, string propertyValue2)  
     {  
       var combinedValue = propertyValue1.Trim() + "." + propertyValue2;  
       // Find the row just below where the new item will be inserted  
       var timesheetItemToIndex = listOfObjects  
         .OrderByDescending(t => t.Property1)  
         .ThenByDescending(t => t.Property2)  
         .FirstOrDefault(  
           t => string.Compare((t.Property1.Trim() + "." + t.Property2), combinedValue ,  
                StringComparison.CurrentCultureIgnoreCase) < 0);  
       // Return the index of the next item  
       if (timesheetItemToIndex == null) return 0;  
       return listOfObjects.IndexOf(timesheetItemToIndex ) + 1;  
     }