Skip to content

Instantly share code, notes, and snippets.

@samandmoore
Created July 18, 2012 23:05
Show Gist options
  • Save samandmoore/3139587 to your computer and use it in GitHub Desktop.
Save samandmoore/3139587 to your computer and use it in GitHub Desktop.
Default Sort for with Lambda
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var sort = SortBuilder<TestClass>.For(s => s.SomeProperty, SortDirection.Ascending);
Console.WriteLine("{0} - {1}", sort.Column, sort.Direction.ToString());
}
}
public class TestClass
{
public int SomeProperty { get; set; }
}
public enum SortDirection
{
Ascending,
Descending
}
public class DefaultSort
{
public DefaultSort(string column, SortDirection direction)
{
this.Column = column;
this.Direction = direction;
}
public string Column { get; private set; }
public SortDirection Direction { get; private set; }
}
public static class SortBuilder<TModel>
{
public static DefaultSort For<TValue>(Expression<Func<TModel, TValue>> expression, SortDirection direction)
{
var memberExp = expression.Body as MemberExpression;
return new DefaultSort(memberExp == null ? null : memberExp.Member.Name, direction);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment