using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Collections;
using
System.Reflection;
using
System.Windows.Forms;
namespace
ReflectOn
{
/// <summary>
///
General Sort Comparer class
///
[Only this class is required while adding to projects]
/// </summary>
public class ReflectionComparer : IComparer
{
private string[]
_sortProperties;
private SortOrder _sortOrder =
SortOrder.Ascending;
/// <summary>
///
ctor 1
/// </summary>
/// <param name="sortProperties"></param>
public ReflectionComparer(params string[] sortProperties)
{
_sortProperties
= sortProperties;
_methodInfos =
new
MethodInfo[sortProperties.Length];
}
/// <summary>
///
ctor 2
/// </summary>
/// <param name="sortOrder"></param>
/// <param name="sortProperties"></param>
public ReflectionComparer(SortOrder sortOrder,
params string[]
sortProperties)
{
_sortOrder =
sortOrder;
_sortProperties
= sortProperties;
_methodInfos =
new
MethodInfo[sortProperties.Length];
}
/// <summary>
///
Core Comparison method
/// </summary>
/// <param name="x">first
object</param>
/// <param name="y">second
object</param>
/// <returns></returns>
public int
Compare(object x,
object y)
{
int result = 0;
for (int i
= 0; i < _sortProperties.Length; i++)
{
string property = _sortProperties[i];
object value1 = GetValue(x, property);
object value2 = GetValue(y, property);
// todo: Check for nulls
if (_sortOrder == SortOrder.Ascending)
result =
(int)GetMethodInfo(value1, i).Invoke(value1,
new object[1]
{ value2 });
else
result = (int)GetMethodInfo(value1,
i).Invoke(value2, new object[1] { value1 });
if (result != 0)
break;
}
return result;
}
private MethodInfo[] _methodInfos;
/// <summary>
///
Returns the "CompareTo" MethodInfo
/// </summary>
/// <param name="value">The
object on which we have to reflect on</param>
/// <param name="index">The
index of property (methods differ based on property]</param>
/// <returns></returns>
private MethodInfo GetMethodInfo(object
value, int index)
{
// Use reflection to get the
CompareTo method from object, reuse previuos method info if exists
if (_methodInfos[index] ==
null)
_methodInfos[index]
= value.GetType().GetMethods().Where(m => m.Name ==
"CompareTo").FirstOrDefault();
return _methodInfos[index];
}
<summary>
/// Returns the value
of the property in given object
/// [Using Reflection]
/// </summary>
/// <param name="obj"></param>
/// <param name="property"></param>
/// <returns></returns>
private object GetValue(object
obj, string property)
{
return obj.GetType().GetProperty(property).GetValue(obj,
null);
}
}
}