[英]How can I select from an included entity in LINQ and get a flat list similar to a SQL Join would give?
I have two classes: 我有两节课:
public class Topic
{
public Topic()
{
this.SubTopics = new HashSet<SubTopic>();
}
public int TopicId { get; set; }
public string Name { get; set; }
public virtual ICollection<SubTopic> SubTopics { get; set; }
}
public class SubTopic
public int SubTopicId { get; set; }
public int Number { get; set; }
public int TopicId { get; set; }
public string Name { get; set; }
public virtual Topic Topic { get; set; }
}
What I would like to do is to get a Data Transfer Object output from LINQ that will show me. 我想做的是从LINQ获取数据传输对象输出,该输出将显示给我。 I do want to see the TopicId repeated if there is more than one SubTopic inside that topic: 如果该主题内有多个SubTopic,我确实希望重复查看TopicId:
TopicId Name SubTopicId Name
1 Topic1 1 SubTopic1
1 Topic1 2 SubTopic2
1 Topic1 3 SubTopic3
2 Topic2 4 SubTopic4
I tried to code a Linq statement like this: 我试图编写这样的Linq语句:
var r = context.Topics
.Select ( s => new {
id = s.TopicId,
name = s.Name,
sid = s.SubTopics.Select( st => st.SubTopicId),
sidname = s.SubTopics.Select ( st => st.Name)
}).
ToList();
But this does not really work as it returns sid and sidname as lists. 但这实际上并不起作用,因为它将sid和sidname返回为列表。
How will it be possible for me to get a flat output showing what I need? 我将如何获得显示我需要的固定输出?
You need SelectMany
to expand a nested collection, along these lines 您需要SelectMany
沿这些行扩展嵌套的集合
var r = context.Topics.SelectMany(t => t.SubTopics
.Select(st => new
{
TopicID = t.TopicId,
TopicName = t.Name,
SubTopicID = st.SubTopicId,
SubTopicName = st.Name
}));
try this : 尝试这个 :
var r = context.Topics
.Select ( s => new {
id = s.TopicId,
name = s.Name,
sid = s.SubTopics.Where(st=>st.TopicId==s.TopicId).Select( st => st.SubTopicId ),
sidname = s.SubTopics..Where(st=>st.TopicId==s.TopicId).Select ( st => st.Name)
}).
ToList();
Hope it will help 希望对你有帮助
@Sweko provided an answer that satisfies the exact output that you requested. @Sweko提供的答案可以满足您要求的确切输出。 However, this can be even simpler if you just return the subtopic intact. 但是,如果只返回完整的子主题,这甚至会更加简单。 It may run a bit quicker as well, since you don't need to create a new object for each element in the result. 由于您不需要为结果中的每个元素创建一个新的对象,它的运行速度也可能会更快一些。
Lastly, it looks like you wanted your result set ordered. 最后,您似乎希望对结果集进行排序。 For completeness, I've added those clauses as well. 为了完整起见,我还添加了这些子句。
var r = context.Topics
.SelectMany( topic => topic.SubTopics )
.OrderBy(sub => sub.TopicId)
.ThenBy(sub => sub.SubTopicId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.