Skip to content

Instantly share code, notes, and snippets.

@DanielSSilva
Created January 4, 2018 18:20
Show Gist options
  • Save DanielSSilva/ecf5bf9144b19bb1c0d113d1c2bf6fc3 to your computer and use it in GitHub Desktop.
Save DanielSSilva/ecf5bf9144b19bb1c0d113d1c2bf6fc3 to your computer and use it in GitHub Desktop.
class Program
{
static void Main(string[] args)
{
IEnumerable<Xpto> enumerable = new List<Xpto>
{
new Xpto(15,"a"),
new Xpto(8,"c"),
new Xpto(3,"e"),
new Xpto(5,"t"),
new Xpto(4,"b"),
new Xpto(2,"v"),
new Xpto(1,"q")
};
IQueryable<Xpto> list = enumerable.AsQueryable();
Expression<Func<Xpto, string>> expression = CreateExpression<Xpto>("_text");
IEnumerable<Xpto> newEnumerable = list.OrderBy(expression);
foreach (Xpto xpto in newEnumerable)
Console.WriteLine($"Id = {xpto._id} and Text = {xpto._text}");
Console.Read();
}
private static Expression<Func<T, string>> CreateExpression<T>(string fieldName)
{
ParameterExpression parameter = Expression.Parameter(typeof(T), "x");
MemberExpression body = Expression.PropertyOrField(parameter, fieldName);
return Expression.Lambda<Func<T, string>>(body, parameter); //x => x.Id
}
}
class Xpto
{
public int _id;
public string _text;
/// <inheritdoc />
public Xpto(int id, string text)
{
_id = id;
_text = text;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment