IEnumerable<动态>linq 表达式动态>
我有动态客户列表 IEnumerable
现在我想从该列表中获得不同的公司名称?
我以为我可以做类似的事情
dynamic cur = (from c in result.Customers
select g.CompanyName).Distinct();
,但今天我发现我不能...... 我怎样才能建立这样的查询?
I have dynamic list of customers IEnumerable<Customer>
now I want to have the disctinct company names from that list?
I thought I could do something like
dynamic cur = (from c in result.Customers
select g.CompanyName).Distinct();
but learned today that I can't...
how can I build a query like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在代码中所做的事情和您在问题标题中提出的问题是两件不同的事情。
如果您想要
IEnumerable
,则必须执行以下操作:from c in result.Customers select g.CompanyName
返回IEnumerable
。Cast()
返回IEnumerable
。Distinct()
返回可枚举的不同成员。默认情况下, 。这会检查正在枚举的类型并尝试找出如何处理它(该链接详细描述了这一点)。
Distinct()
使用默认的相等比较器 EqualityComparer这一切都如宣传的那样工作,除非默认的相等比较器无法处理动态处理的类型。在这种情况下,您必须使用采用自定义相等比较器的覆盖。
What you are doing in code and what you are asking in the title of your question are two different things.
If you want
IEnumerable<dynamic>
you must do the following:from c in result.Customers select g.CompanyName
returnsIEnumerable<string>
.Cast<dynamic>()
returnsIEnumerable<dynamic>
.Distinct()
returns distinct members of the enumerable.Distinct()
uses, by default, the default equality comparer EqualityComparer<T>. This examines the type being enumerated and tries to figure out how to handle it (the link describes this in detail).This all works as advertised, unless the type being handled dynamically can't be handled by the default equality comparer. In this case, you'll have to use the override that takes a custom equality comparer.
只要
Customer
类有一个成员CompanyName
,您就绝对可以执行以下操作:使用
dynamic
关键字比dynamic
没有任何优势。 code>var 在这里,除了它可以防止编译器错误出现之外。As long as the
Customer
class has a memberCompanyName
, you can definitely do the following:There is no advantage to using the
dynamic
keyword overvar
here, other than the fact that it will prevent compiler errors from appearing.