帮助选择中的 Linq 和动态对象属性

发布于 2024-10-21 13:41:04 字数 641 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暗喜 2024-10-28 13:41:04

试试这个:

o.GetType().GetProperty("Number").GetValue(o)

...在您的 Select 子句中。

Try this instead:

o.GetType().GetProperty("Number").GetValue(o)

...in your Select clause.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文