如何使用反射值创建 OrderBy 语句?
我想创建一个方法,通过给定的属性对 IEnumerable 列表进行排序,其中该属性通过字符串 ie 传递到该方法中(请注意,第一个代码示例不起作用,但第二个代码示例起作用,这就是我想要的动态模拟)。
string sortName = "SerialNumber";
IEnumerable<PartSummary> partList = FunctionToCreateList();
partOrderedList = partList.OrderBy(what do I stick in here);
这相当于
IEnumerable<PartSummary> partList = FunctionToCreateList();
partOrderedList = partList.OrderBy(p => p.SerialNumber);
我怎样才能做到这一点?
I would like to create a method that orders an IEnumerable List by a given property where the property is passed into the method by a string i.e. (Mind you the first code example does not work, but the second does and is what I am trying to emulate dynamically).
string sortName = "SerialNumber";
IEnumerable<PartSummary> partList = FunctionToCreateList();
partOrderedList = partList.OrderBy(what do I stick in here);
that would be equivalent to
IEnumerable<PartSummary> partList = FunctionToCreateList();
partOrderedList = partList.OrderBy(p => p.SerialNumber);
How can I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是说您想将订单传递给您的方法吗?如果是这样,您可以使用以下命令:
然后您可以执行以下操作:
然后您可以在业务层或任何您希望的位置处理您的订单。
好的,更新:如果您想将列名作为字符串传递,您可以执行如下操作:
为扩展方法创建一个静态类(参考:http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/39028ad2-452e-409f-bc9e-d1b263e921f6/):
然后您可以创建您的方法:
然后调用您的方法:
现在您可以将列名称作为字符串传递并进行排序。
希望这有帮助!
Are you saying you want to pass the order by in to your method? If so, you can use this:
Then you can do this:
Then you can handle your order by in your business layer or wherever you wish.
Okay, update: If you want to pass in the column name as a string you can do something like as follows:
Create a static class for an extension method (reference: http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/39028ad2-452e-409f-bc9e-d1b263e921f6/):
Then you can create your method:
And then call your method:
Now you can pass in the column name as a string and sort.
Hope this helps!
您还可以避免扩展,只使用编译的表达式树来完成此操作:
You can also avoid extending and just use a compiled expression tree to accomplish this: