简体   繁体   English

IEnumerable的 <dynamic> linq表达

[英]IEnumerable<dynamic> linq expressions

I have dynamic list of customers IEnumerable<Customer> 我有动态的客户名单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? 但今天学到了我不能......我怎么能建立这样的查询呢?

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: 如果您想要IEnumerable<dynamic>您必须执行以下操作:

IEnumerable<dynamic> cur = (from c in result.Customers
               select g.CompanyName).Cast<dynamic>().Distinct();

from c in result.Customers select g.CompanyName returns IEnumerable<string> . from c in result.Customers select g.CompanyName返回IEnumerable<string>
Cast<dynamic>() returns IEnumerable<dynamic> . Cast<dynamic>()返回IEnumerable<dynamic>
Distinct() returns distinct members of the enumerable. Distinct()返回可枚举的不同成员。

Distinct() uses, by default, the default equality comparer EqualityComparer<T> . 默认情况下, Distinct()使用默认的相等比较器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. 在这种情况下,您将必须使用带有自定义相等比较器的覆盖。

As long as the Customer class has a member CompanyName , you can definitely do the following: 只要Customer类具有成员CompanyName ,您肯定可以执行以下操作:

var companies = (from c in result.Customers
                 select c.CompanyName).Distinct();

There is no advantage to using the dynamic keyword over var here, other than the fact that it will prevent compiler errors from appearing. 这里使用dynamic关键字对var没有任何好处,除了它会阻止编译器错误出现的事实。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM