Thursday, August 14, 2008

Multi Sorting array of objects

A method sort (asc and desc) array of objects by properties and return sorted array.
private static T[] MultiSortObjectArray<T>(T[] objects,
bool isReverseSort, params string[] propertyNames)
{
//Get array object type
PropertyInfo[] propertiesInfo = (typeof (T)).GetProperties();
//Define list of properties for sorting
List<PropertyInfo> lstProperties2Compare = new List<PropertyInfo>();

//Check sorting properties one by one
foreach (string sortPropertyName in propertyNames)
{
//Find sorting property in Object property
PropertyInfo sortProperty =
Array.Find(propertiesInfo,
delegate(PropertyInfo property)
{
return (
string.Compare(property.Name, sortPropertyName,
true) == 0
);
}
);

//Add existing property to sorting list
if (sortProperty != null)
lstProperties2Compare.Add(sortProperty);
}

if (lstProperties2Compare.Count == 0)
return null;

Array.Sort(objects,
delegate(T x, T y)
{
int result = -1;
foreach (PropertyInfo propInfo2Compare in
lstProperties2Compare)
{
result = (!isReverseSort)
? //Sort by asc
(new CaseInsensitiveComparer()).Compare(
propInfo2Compare.GetValue(x, null),
propInfo2Compare.GetValue(y, null)
)
: //Sort by desc
(new CaseInsensitiveComparer()).Compare(
propInfo2Compare.GetValue(y, null),
propInfo2Compare.GetValue(x, null)
);
//If x equals y continue compare process
if (result != 0)
break;
}

return result;
}
);

return objects;
}





kick it on DotNetKicks.com