Writing an extension method to help with querying many-to-many relationships

Viewed 418

I am trying to write an extension method in order to refactor a linq many-to-many query I'm writing. I am trying to retrieve a collection of Post(s) which have been tagged with any of the Tag(s) in a collection passed as a parameter to my method.

Here are the relevant entities along with some of their properties:

Post

Scalar Properties: PostID, PostDate

Navigation Property: PostTags

PostTag

Scalar Properties: PostTagID, PostID, TagID

Navigation Properties: Post, Tag

Tag

Scalar Properties: TagID

Navigation Property: PostTags

This is the query I'm currently using which works well:

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;               
}   

This is the (probably incorrect) start of the extension method I'm struggling to create:

public static IEnumerable<TResult> SelectRange<TSource, TResult>(
    this IEnumerable<TSource> collection,
    Func<IEnumerable<TSource>, IEnumerable<TResult>> selector)
{
    return selector(collection);
}

And the ideal simplification of the original query:

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;
}

Any help in writing this extension method, or any other more efficient way to perform this query, will be greatly appreciated.

3 Answers
Related