I have a model:
public class SomeClass {
public List<Person> Owner {get; set;}
public int Balance {get;set;}
. . . .
}
and
public class Person {
public string Name {get;set;}
public Guid PersonID {get;set;}
. . . .
}
I have a wrapper class which handles the sorting:
public class SortedResult <ModelType>: Result where ModelType: new() {
. . . .
private void SetProperties(IQueryable <ModelType> data, int pageIndex, int pageSize, string orderBy, OrderDirection ? orderDir) {
if (!String.IsNullOrEmpty(orderBy)) {
// auto-handles the order-by
if (orderDir == OrderDirection.Descending) {
data = data.OrderByDescending(orderBy);
} else {
data = data.OrderBy(orderBy);
}
}
int total = data.Count();
// no ordering
Data = data.Skip(pageIndex * pageSize).Take(pageSize).ToList();
AllData = myIncludeAllData ? data : null;
PageIndex = pageIndex;
PageSize = pageSize;
TotalSize = total;
}
}
As you can see, SortedResult
allows me to sort any List<T>
dynamically. Sorting using other properties of SomeClass
runs ok but when I sort by the Owner
property, I'm getting error:
"At least one object must implement IComparable."
I am guessing that it's because the system doesn't know how to sort List<SomeClass>
by the Owner
property.
How can I allow SomeClass
to be sorted by Owner.Name
if it is sorted using Owner
? I have seen examples that overrides the Compare
logic of the model but I don't know where to start.
Any help will be very much appreciated.
EDIT:
@dasblinkenlight's comment enlightened me. Indeed, it is wrong to sort by Owner
which is a List<Person>
.
For the fix, I modified my SomeClass
model:
public class SomeClass {
public List<Person> Owner {get; set;}
//should sort using this prop instead of Owner
public string OwnerName { get
{ return string.Join(", ", this.Owner.Select(r => r.Name)); }
}
public int Balance {get;set;}
. . . .
}
Thanks for all the effort everyone.