如何根据我传过来的参数进行排序呢????? List<ROOMREPORT> roomreports = new List<ROOMREPORT>();ROOMREPORT是个类,有七八个属性····我想根据我传过来的参数,返回这个集合排序后的集合但是因为属性太多,也不能一个个if来判断把····求大家帮帮看看   roomreports.OrderBy(r => r.DOCUMENT_NUM)DOCUMENT_NUM这个想换成参数的形式能做到吗???

解决方案 »

  1.   

    什么意思没看懂//查询DOCUMENT_NUM是你的参数的roomreports.OrderBy(r => r.DOCUMENT_NUM==“你的参数”)
      

  2.   

    用反射:
    http://blog.csdn.net/q107770540/article/details/6133484
      

  3.   

    EX:class Pet
    {
       public string Name{get;set;}
       public int Age{get;set;}
    }
    void Main()

          Pet[] pets = { new Pet { Name="Tim", Age=18 },
                       new Pet { Name="Allen", Age=22 },
                       new Pet { Name="Bill", Age=20  } };
         
    //如果我们想根据Age进行排序  很容易想到这样来写:
      var query= from p in pets
                 orderby p.Age
                 select p;
                 
         
      query.ToList().ForEach(q=>Console.WriteLine(q.Name +"     "+q.Age));
            /* 得到结果: 
            Tim     18
            Bill    20
            Allen   22
            */
            
    }
    //但是有时项目内有多个排序条件 如有时要根据Name排序 有时要根据Age排序
           //这时我们就要用到动态排序:
    void Main()

        Pet[] pets = { new Pet { Name="Tim", Age=18 },
                       new Pet { Name="Allen", Age=22 },
                       new Pet { Name="Bill", Age=20 } };
        Console.WriteLine("Before Orderby:/r/n");       
        pets.ToList().ForEach(p=>Console.WriteLine(p.Name +"     "+p.Age));
         
      var query= from p in pets
                 orderby GetPropertyValue(p,"Age")  
                 select p;
                 
        Console.WriteLine("/r/nAfter Orderby:/r/n");
      query.ToList().ForEach(q=>Console.WriteLine(q.Name +"     "+q.Age));
               /*
            Before Orderby:
            Tim     18
            Allen   22
            Bill    20
            After Orderby:
            
            Tim     18
            Bill    20
            Allen   22
            */       
    }
    private static object GetPropertyValue(object obj, string property)
    {
        System.Reflection.PropertyInfo propertyInfo=obj.GetType().GetProperty(property);
        return propertyInfo.GetValue(obj, null);
    }
      

  4.   

    就是我想排序,排序的字段是参数~~~~参数是这个类的属性名(不是属性值)我的意思是想要实现roomreports.OrderBy(r => r.参数)
      

  5.   

    就是我想排序,排序的字段是参数~~~~参数是这个类的属性名(不是属性值)我的意思是想要实现roomreports.OrderBy(r => r.参数)额 看错了   要使用属性名,只要用反射
      

  6.   

    roomreports.OrderBy(r => r.GetType().GetProperty("要排序的属性名").GetValue(t,null));
      

  7.   

    C# 4.0的最佳做法:
    var param = Expression.Parameter(typeof(ROOMREPORT));
    var lambda = Expression.Lambda(Expression.MakeMemberAccess(param, typeof(ROOMREPORT).GetProperty("要排序的属性名")), param);
    var query = roomreports.OrderBy(lambda.Compile() as Func<ROOMREPORT, string>); //假设属性是string类型