M
MattC
Hi,
I found this code somewhere on the net and need to make some alterations.
public class GenericSorter : IComparer
{
String sortProperty;
bool sortOrder;
public GenericSorter(String sortBy, bool asc)
{
sortProperty = sortBy;
sortOrder = asc;
}
public int Compare(object x, object y)
{
IComparable ic1 =
(IComparable)x.GetType().GetProperty(sortProperty).GetValue(x,null);
IComparable ic2 =
(IComparable)y.GetType().GetProperty(sortProperty).GetValue(y,null);
if(sortOrder)
return ic1.CompareTo(ic2);
else
return ic2.CompareTo(ic1);
}
}
It works fine if the property to sort on is in the current object, for
example ID. However, if I pass sortProperty string such as
"thisDepartment.ID" (in order to sort by the department that the object
belings to).
Is there a way to use GetProperty to evaulate and navigate to the property
in question and then get its value?
So far I have come up with the follwing solutions.
1.) Call GetProperties() and find the first property, search for another '.'
if there isnt one then get the value of the string after the '.'. If there
is another '.' get the propoerties for that property, and so on with
recursion. Bit of a killer in terms of performance, but how else can you
provide the ability to sort on any property in an object model?
2.) Scrap the generic sorter and implement a sort for each property I want
to sort on that does the navigation. requires lots of code.
Any ideas would be cool.
TIA
MattC
I found this code somewhere on the net and need to make some alterations.
public class GenericSorter : IComparer
{
String sortProperty;
bool sortOrder;
public GenericSorter(String sortBy, bool asc)
{
sortProperty = sortBy;
sortOrder = asc;
}
public int Compare(object x, object y)
{
IComparable ic1 =
(IComparable)x.GetType().GetProperty(sortProperty).GetValue(x,null);
IComparable ic2 =
(IComparable)y.GetType().GetProperty(sortProperty).GetValue(y,null);
if(sortOrder)
return ic1.CompareTo(ic2);
else
return ic2.CompareTo(ic1);
}
}
It works fine if the property to sort on is in the current object, for
example ID. However, if I pass sortProperty string such as
"thisDepartment.ID" (in order to sort by the department that the object
belings to).
Is there a way to use GetProperty to evaulate and navigate to the property
in question and then get its value?
So far I have come up with the follwing solutions.
1.) Call GetProperties() and find the first property, search for another '.'
if there isnt one then get the value of the string after the '.'. If there
is another '.' get the propoerties for that property, and so on with
recursion. Bit of a killer in terms of performance, but how else can you
provide the ability to sort on any property in an object model?
2.) Scrap the generic sorter and implement a sort for each property I want
to sort on that does the navigation. requires lots of code.
Any ideas would be cool.
TIA
MattC