编写扩展方法以帮助查询多对多关系

ali*_*ray 12 c# linq extension-methods linq-to-entities

我正在尝试编写一个extension method以重构我正在编写的linq多对多查询.我正在尝试检索一个集合,Post(s)该集合已被标记Tag(s)为作为参数传递给我的方法的集合中的任何集合.

以下是相关实体及其部分属性:

岗位

标量属性:PostID,PostDate

导航属性:PostTags

PostTag

标量属性:PostTagID,PostID,TagID

导航属性:Post,Tag

标签

标量属性:TagID

导航属性:PostTags

这是我目前使用的查询效果很好:

public IEnumerable<Post> GetPostsByTags(IEnumerable<Tag> tags)
{
    return from pt in context.PostTags
           from t in tags
           where pt.TagID == t.TagID &&
                 pt.Post.PostDate != null
           orderby pt.Post.PostDate descending
           select pt.Post;               
}   
Run Code Online (Sandbox Code Playgroud)

这是extension method我正在努力创建的(可能不正确的)开始:

public static IEnumerable<TResult> SelectRange<TSource, TResult>(
    this IEnumerable<TSource> collection,
    Func<IEnumerable<TSource>, IEnumerable<TResult>> selector)
{
    return selector(collection);
}
Run Code Online (Sandbox Code Playgroud)

并且原始查询的理想简化:

public IEnumerable<Post> GetPostsByTags(IEnumerable<Tag> tags)
{
    return from p in context.Posts
           where p.PostTags.SelectRange(x => ?) &&
                 p.PostDate != null                    
           orderby p.PostDate descending
           select p;
}
Run Code Online (Sandbox Code Playgroud)

任何帮助写这个extension method,或任何其他更有效的方式来执行此查询,将不胜感激.

Adu*_*cci 2

我认为你原来的查询很好,你只需要处理重复的帖子。在末尾添加一个不同的。或者您可以像这样使用 Any 方法。

public IEnumerable<Post> GetPostsByTags(IEnumerable<Tag> tags)
{
    return from p in context.Posts
           where p.PostTags.Any(pt => tags.Any(t => t.TagID == pt.TagID)) &&
                 p.PostDate != null                    
           orderby p.PostDate descending
           select p;
}
Run Code Online (Sandbox Code Playgroud)

编辑 - 添加了另一个 Any 语句