IEnumerable<dynamic> linq expressions
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).D开发者_JAVA技巧istinct();
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> cur = (from c in result.Customers
select g.CompanyName).Cast<dynamic>().Distinct();
from c in result.Customers select g.CompanyName
returns IEnumerable<string>
.
Cast<dynamic>()
returns IEnumerable<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.
As long as the Customer
class has a member CompanyName
, you can definitely do the following:
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.
精彩评论