SelectMany 展平一系列序列
var sequenceOfSequences = new [] { new [] { 1, 2, 3 }, new [] { 4, 5 }, new [] { 6 } };
var sequence = sequenceOfSequences.SelectMany(x => x);
// returns { 1, 2, 3, 4, 5, 6 }
如果有,请使用 SelectMany()
,或者你正在创建序列序列,但是你希望将结果作为一个长序列。
在 LINQ 查询语法中:
var sequence = from subSequence in sequenceOfSequences
from item in subSequence
select item;
如果你有一个集合集合,并希望能够同时处理来自父集合和子集合的数据,那么也可以使用 SelectMany
。
我们来定义简单的类
public class BlogPost
{
public int Id { get; set; }
public string Content { get; set; }
public List<Comment> Comments { get; set; }
}
public class Comment
{
public int Id { get; set; }
public string Content { get; set; }
}
我们假设我们有以下收集。
List<BlogPost> posts = new List<BlogPost>()
{
new BlogPost()
{
Id = 1,
Comments = new List<Comment>()
{
new Comment()
{
Id = 1,
Content = "It's really great!",
},
new Comment()
{
Id = 2,
Content = "Cool post!"
}
}
},
new BlogPost()
{
Id = 2,
Comments = new List<Comment>()
{
new Comment()
{
Id = 3,
Content = "I don't think you're right",
},
new Comment()
{
Id = 4,
Content = "This post is a complete nonsense"
}
}
}
};
现在我们要选择评论 Content
以及与此评论相关的 BlogPost
的 Id
。为了做到这一点,我们可以使用适当的 SelectMany
重载。
var commentsWithIds = posts.SelectMany(p => p.Comments, (post, comment) => new { PostId = post.Id, CommentContent = comment.Content });
我们的 commentsWithIds
看起来像这样
{
PostId = 1,
CommentContent = "It's really great!"
},
{
PostId = 1,
CommentContent = "Cool post!"
},
{
PostId = 2,
CommentContent = "I don't think you're right"
},
{
PostId = 2,
CommentContent = "This post is a complete nonsense"
}