I am writing an extension method that allows me to do an OrderBy on an IEnumerable list object using a string instead of a Lambda expression. It works okay for simple properties. However, I'm trying to figure out how to allow for nested properties.
If my Models looks like this:
public class Submission
{
public int SubmissionId {get; set;}
public string Description {get; set;}
public int ProjectId {get; set;}
// Parent object
public Project ParentProject {get; set;}
}
public class Project
{
public int ProjectId {get; set;}
public string FullTitle {get; set;}
}
I can do an OrderBy using this:
public static class MkpExtensions
{
public static IEnumerable<T> OrderByField<T>(this IEnumerable<T> list, string sortExpression)
{
sortExpression += "";
string[] parts = sortExpression.Split(' ');
bool descending = false;
string fullProperty = "";
if (parts.Length > 0 && parts[0] != "")
{
fullProperty = parts[0];
if (parts.Length > 1)
{
descending = parts[1].ToLower().Contains("esc");
}
ParameterExpression inputParameter = Expression.Parameter(typeof(T), "p");
Expression propertyGetter = inputParameter;
foreach (string propertyPart in fullProperty.Split('.'))
{
PropertyInfo prop = propertyGetter.Type.GetProperty(propertyPart);
if (prop == null)
throw new Exception("No property '" + fullProperty + "' in + " + propertyGetter.Type.Name + "'");
propertyGetter = Expression.Property(propertyGetter, prop);
}
// This line was needed
Expression conversion = Expression.Convert(propertyGetter, typeof(object));
var getter = Expression.Lambda<Func<T, object>>(propertyGetter, inputParameter).Compile();
if (descending)
return list.OrderByDescending(x => prop.GetValue(x, null));
else
return list.OrderBy(x => prop.GetValue(x, null));
}
return list;
}
}
And my code would have this:
public List<Submission> SortedSubmissions (bool simple = true) {
var project1 = new Project { ProjectId = 1, FullTitle = "Our Project"};
var project2 = new Project { ProjectId = 2, FullTitle = "A Project"};
List<Submission> listToSort = new List<Submission>
{
new Submission { SubmissionId = 1, Description = "First Submission",
ProjectId = project1.ProjectId, ParentProject = project1 } ,
new Submission { SubmissionId = 2, Description = "Second Submission",
ProjectId = project1.ProjectId, ParentProject = project1 } ,
new Submission { SubmissionId = 3, Description = "New Submission",
ProjectId = project2.ProjectId, ParentProject = project2 }
};
var simpleField = "Description";
// This would have the submissions sorted (1, 3, 2)
var simpleSort = listToSort.OrderByField(simpleField + " asc").ToList();
// Need to see if I can get this to work
var nestedField = "Project.FullTitle";
// This would have the submissions sorted (3, 1, 2)
return listToSort.OrderByField(nestedField + " asc").ToList();
}
I hope I'm explaining myself clearly. Can this be done?
Update: I used André Kops code and adjusted above, but get this error: System.Nullable'1[System.Int32]' cannot be used for return type 'System.Object'