Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Reflection and Linq Extension Methods

Reflection and Linq Extension Methods

Scheduled Pinned Locked Moved C#
linqcsharpfunctionaltutorialquestion
2 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • G Offline
    G Offline
    Gustavo Ushijima
    wrote on last edited by
    #1

    I have this code:

    public static IQueryable<T> OrderBy<T>(
    this IQueryable<T> source, string propertyName, string order)
    {
    var type = typeof(T);
    var asc = order == "asc" ? true:false;
    string methodName = asc ? "OrderBy" : "OrderByDescending";

            var parameter = Expression.Parameter(type, "p");
            var property = type.GetProperty(propertyName);
    
            var propertyAccess = Expression.MakeMemberAccess(parameter, property);
            var orderByExp = Expression.Lambda(propertyAccess, parameter);
    
            MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName,
                              new Type\[\] { type, property.PropertyType },
                              source.Expression, Expression.Quote(orderByExp));
            return source.Provider.CreateQuery<T>(resultExp);
        }
    

    And i would like to extend it to allow child properties, like "Address.Street" if i pass just a simple property it works nice... but i want to make it better and accept child object property to make order by. Anyone knows how to modify it? I tryed but no success... i don't know how to make it to find the child object property and create the MemberAccess with it X| Thanks!!

    O 1 Reply Last reply
    0
    • G Gustavo Ushijima

      I have this code:

      public static IQueryable<T> OrderBy<T>(
      this IQueryable<T> source, string propertyName, string order)
      {
      var type = typeof(T);
      var asc = order == "asc" ? true:false;
      string methodName = asc ? "OrderBy" : "OrderByDescending";

              var parameter = Expression.Parameter(type, "p");
              var property = type.GetProperty(propertyName);
      
              var propertyAccess = Expression.MakeMemberAccess(parameter, property);
              var orderByExp = Expression.Lambda(propertyAccess, parameter);
      
              MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName,
                                new Type\[\] { type, property.PropertyType },
                                source.Expression, Expression.Quote(orderByExp));
              return source.Provider.CreateQuery<T>(resultExp);
          }
      

      And i would like to extend it to allow child properties, like "Address.Street" if i pass just a simple property it works nice... but i want to make it better and accept child object property to make order by. Anyone knows how to modify it? I tryed but no success... i don't know how to make it to find the child object property and create the MemberAccess with it X| Thanks!!

      O Offline
      O Offline
      onelopez
      wrote on last edited by
      #2

      There you go, sorts on properties of properties... not quite sure if it works with methods. The logic is there, but it's not fully tested

       public static IEnumerable SortObject(this IEnumerable ObjectToSort, string SortBy)
          {
              if (ObjectToSort == null)
                  return null;
              if (string.IsNullOrEmpty(SortBy) == true)
                  return null;
      
      		// Handle sorting on object methods as well as properties
              string\[\] tempSorts = SortBy.Split(',');
              List SortList = new List();
              bool inParanthese = false;
              string addString = string.Empty;
              foreach (string tempSort in tempSorts)
              {
                  if ((tempSort.Contains("(") == true) && (tempSort.Contains(")") == false))
                  {
                      inParanthese = true;
                  }
                  else if (tempSort.Contains(")") == true)
                  {
                      inParanthese = false;
                  }
                  if (inParanthese == false)
                  {
                      if (string.IsNullOrEmpty(addString) == false)
                      {
                          SortList.Add(addString + "," + tempSort.Trim());
                      }
                      else
                      {
                          SortList.Add(tempSort);
                      }
                      addString = string.Empty;
                  }
                  else
                  {
                      if (string.IsNullOrEmpty(addString) == false)
                          addString += ",";
                      addString += tempSort.Trim();
                  }
              }
              string\[\] Sorts = SortList.ToArray();
              bool Sorted = false;
              foreach (string FieldSort in Sorts)
              {
                  string\[\] SubSort = FieldSort.Trim().Split(' ');
      
                  string\[\] props = SubSort\[0\].Split('.');
                  Type type = typeof(T);
                  ParameterExpression arg = Expression.Parameter(type, "x");
                  Expression expr = arg;
                  foreach (string prop in props)
                  {
                      System.Reflection.PropertyInfo pi = type.GetProperty(prop);
                      if (pi != null)
                      {
                          Sorted = true;
                          //expr = Expression.Property(expr, pi);
                          expr = Expression.MakeMemberAccess(expr, pi);
      
      1 Reply Last reply
      0
      Reply
      • Reply as topic
      Log in to reply
      • Oldest to Newest
      • Newest to Oldest
      • Most Votes


      • Login

      • Don't have an account? Register

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • World
      • Users
      • Groups