News - Filter by Category Linq expression
Does anyone know how to filter the news items to only include a certain category?
As I understand it the categories are a meta key of the content, but how on earth do you get at it from a linq expression.
I'm trying to do something like:
NewsManager newsManager = NewsManager.GetManager();
IQueryable<NewsItem> allNews = newsManager.GetNewsItems();
foreach
(NewsItem newsItem
in
allNews.SelectMany(t => t.Content. ..... something to filter categories here .....))
Hmmm. After digging around and cobbling together the information from:
http://www.sitefinity.com/devnet/forums/sitefinity-4-x/general-discussions/category-for-the-current-newsitem.aspx#1390721
I've finally cracked it. Please forgive the franken-code!
var newsManager = NewsManager.GetManager();
var taxonomyManager = TaxonomyManager.GetManager();
var c =
"categories"
;
var taxonomy = taxonomyManager.GetTaxonomies<HierarchicalTaxonomy>().Where(t => t.Name == c).SingleOrDefault();
var b = taxonomy.Taxa.Where(t => t.Name ==
"InformationandOutages"
).SingleOrDefault();
Guid categoryID = b.Id;
IQueryable<NewsItem> allNews = newsManager.GetNewsItems()
.Where(t => ((IList<Guid>)t.GetValue<IList<Guid>>(
"Category"
)).Contains(categoryID))
.Where(t => t.Status == ContentLifecycleStatus.Live);
foreach
(NewsItem newsItem
in
allNews)
...
PS: Surely exposing the Categories in something like a usable interface has got to be on the wish list?!
I sure hope so as well Paul! I'm looking to query news items by category via Fluent as well and getting frustrated. I will try your approach.
Hi Craig,
One gotcha to be aware of: the category "name" used in the linq expression to retrieve the category ID is the "developer name" from the advanced section in the category config - it seems to be the category title with the spaces taken out.
In my case:
Information and Outages = InformationandOutages
Caught me out at first. Hope that helps!
Paul