使用列表的列表作为 IEnumerable.ToLookup() 的查找属性
我有一个如下所示的类:
public class Person
{
public string Name { get; set; }
public DateTime Birthdate { get; set; }
public List<string> PersonalEffects {get; set; }
}
我有一个 List
,我想使用 IEnumerable
并使用每个效果的名称作为键,具有该效果的字符作为值。示例输出:
Cutlass (the Effect)
Jack Sparrow (Person)
Will Turner
Pistol
Jack Sparrow
Hector Barbossa
Davy Jones
但是,我的 LINQ-fu 失败了。我可以通过字典和多个 ForEach 循环来完成此操作,但它看起来并不那么干净(即使它最终确实是同一件事)。
如何在 C# 中使用 ToLookup()
来执行此操作?
I have a class that looks like this:
public class Person
{
public string Name { get; set; }
public DateTime Birthdate { get; set; }
public List<string> PersonalEffects {get; set; }
}
I have a List<Person>
, and I'd like to use the IEnumerable<T>.ToLookup()
and use the name of each effect as the key, with the characters that have that effect as the values. Sample output:
Cutlass (the Effect)
Jack Sparrow (Person)
Will Turner
Pistol
Jack Sparrow
Hector Barbossa
Davy Jones
However, my LINQ-fu is failing me. I can do this through a Dictionary and a number of ForEach loops, but it doesn't seem as clean (even though it does end up being the same thing).
How can I do this using ToLookup()
in C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是可行的:
我们在这里所做的本质上是人物和效果的结合,创建人物+效果对(其中特定的人物和效果可以分别出现在许多对中),然后按效果对这些对进行分组并收集拥有可枚举序列中的每个效果。
This would work:
What we 're doing here is essentially a join of persons and effects, creating person+effect pairs (where both specific persons and effects can appear in many pairs each), then grouping these pairs by effect and collecting the persons posessing each effect in an enumerable sequence.
基本上,您必须首先将列表展平成对。您可以使用很少使用的(至少对我来说)
SelectMany( )
重载:Basically you will have to flatten the list first into pairs. You can do this with a rarely used (at least for me)
SelectMany()
overload:对于好奇的人,之前答案的查询理解语法:
QueryComprehension syntax of the previous answers for the curious: