C# 从 IGrouping 中选择不同的值
我有两个类:
class Foo
{
public Bar SomeBar { get; set; }
}
class Bar
{
public string Name { get; set; }
}
我有一个将 Foos 分组在一起的列表:
var someGroup = from f in fooList
orderby f.SomeBar.Name ascending
group f by f.SomeBar.Name into Group
select Group;
如何从 someGroup 中获取不同 Bars 的列表?
I have two classes:
class Foo
{
public Bar SomeBar { get; set; }
}
class Bar
{
public string Name { get; set; }
}
I have a list of Foos that I group together:
var someGroup = from f in fooList
orderby f.SomeBar.Name ascending
group f by f.SomeBar.Name into Group
select Group;
How can I get the list of the distinct Bars from someGroup?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是否可能会有多个同名酒吧? 如果是这样,那就麻烦了。 如果没有,您可以将其更改为:
或者,如果您只想要每个 name 一个 Bar,您可以坚持原来的查询,但更改最后一位:
这将采用每个中的第一个 Foo组,并找到其 Bar。
Will there potentially be more than one Bar with the same name? If so, it's tricky. If not, you could just change it to:
Alternatively, if you only want one Bar per name, you could stick with your original query, but change the last bit:
This will take the first Foo in each group, and find its Bar.
如果您通过
Bar
的特殊Equals
实现来定义“不同”,则可以使用:If you define "being distinct" by a special
Equals
implementation forBar
, you could use:以前有人问过类似的问题,所以我结合大家的知识做了这个:
它的作用是:
a。 第一行选择您选择的不同项目,这就是您想要的。
b. 第二行通过构造新的 T2 列表将旧 type1 转换为新 type2。
也许你的问题有点过分了,直接删掉你不需要的东西吧。
People asked similar questions before, So I have made this combining everyone's knowledge:
What it does is:
a. First line selects distinct items of your choice, which is what you wanted.
b. Second line converts old type1 to new type2 by constructing new T2 list.
Maybe overkilled for your question, just chop out things you don't need.