IEnumerable<动态>linq 表达式

发布于 2024-10-25 12:22:14 字数 275 浏览 1 评论 0原文

我有动态客户列表 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 技术交流群。

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

发布评论

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

评论(2

﹏半生如梦愿梦如真 2024-11-01 12:22:14

您在代码中所做的事情和您在问题标题中提出的问题是两件不同的事情。

如果您想要 IEnumerable,则必须执行以下操作:

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

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:

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.

獨角戲 2024-11-01 12:22:14

只要 Customer 类有一个成员 CompanyName,您就绝对可以执行以下操作:

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

使用 dynamic 关键字比 dynamic 没有任何优势。 code>var 在这里,除了它可以防止编译器错误出现之外。

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.

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