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:
- From the item to be inserted, combine its values for the two properties into a single string.
- Sort the list of generic list of objects in descending order by the the first property, and then the second.
- 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".
- If there are no items with a lesser combined value return 0. I.E. insert the new item first in the list.
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;
}