帮助选择中的 Linq 和动态对象属性
Linq 新手警报会发出相当大的声音,可能还有一般的新手警报,但我必须问这个问题,因为它让我发疯。我有一个对象 MyObject,它有一些属性,例如 ID、Number。属性的数量远多于 2 个,但您明白了。
我有这些对象的通用列表。从此列表中,我需要根据 MyObject 的动态设置属性生成项目子集。因此,
Dim lst as New List(Of MyObject)
... code to populate list ...
Dim newlist = (From o In lst Select o.Number Distinct).ToList()
我不想拥有一些允许我动态查询选择中对象的属性的东西,例如
Dim lst as New List(Of MyObject)
... code to populate list ...
Dim newlist = (From o In lst Select o.GetType().GetProperty("Number").Name Distinct).ToList()
显然上面的方法不起作用,因为它只是返回属性名称的单项列表。是否有一种相对简单的方法可以在 Linq 语句中动态选择对象属性?
任何和所有的帮助将不胜感激。 谢谢!
The Linq newb alarm is going to sound off rather loudly, and probably the general newb alarm as well, but I have to ask this question because it's driving me nuts. I have an object MyObject that has a handful of properties, e.g. ID, Number. There are many more properties than 2, but you get the idea.
I have a generic List of these objects. From this list I have a requirement to generate a subset of items based on a dynamically set property of MyObject. So, instead of having
Dim lst as New List(Of MyObject)
... code to populate list ...
Dim newlist = (From o In lst Select o.Number Distinct).ToList()
I would like to have something that allows me to query a property of the object in the select dynamically, such as
Dim lst as New List(Of MyObject)
... code to populate list ...
Dim newlist = (From o In lst Select o.GetType().GetProperty("Number").Name Distinct).ToList()
Obviously the above doesn't work as it just returns me a single-item list of the property name. Is there a relatively simple way to select an object property dynamically in a Linq statement?
Any and all help would be appreciated.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
...在您的 Select 子句中。
Try this instead:
...in your Select clause.