I have a method which takes an array of strings as parameter and queries against a collection property which is also a collection of strings. If that property has one of the values inside the string array passed as parameter, it should be returned.
Here is my code:
public IEnumerable<BlogPost> GetAll(string[] tags,
bool includeUnapprovedEntries = false) {
foreach (var tag in tags) {
foreach (var blogPost in GetAll(includeUnapprovedEntries).
ToList().Where(x => x.Tags.Any(t => t == tag))) {
yield return blogPost;
}
}
}
Note:
Here is the complete code:
This does the job but it just doesn’t seem right. I could have made this better with some extension methods but couldn’t figure out what would do the trick and make this implementation right.
Any idea?
How about this:
You may want to call
ToList()to materialize the result. Note that this will (hopefully!) result in anINquery in SQL; if you have a large number of tags, I wouldn’t be surprised if that failed. (I don’t know how the Entity Framework handles that situation.) I believe it should be okay with smaller numbers of tags though.Note that whether or not this is supported may depend on the version of the entity framework you’re using; I seem to remember that some transformations like this (using
Containson a “local” collection) to translate to IN in SQL) have improved over time. Make sure you develop against the same version you’ll be deploying against 🙂