News - Filter by Category Linq expression

Posted by Community Admin on 03-Aug-2018 12:15

News - Filter by Category Linq expression

All Replies

Posted by Community Admin on 07-Jun-2011 00:00

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 .....))

Anyone...?

Paul

Posted by Community Admin on 07-Jun-2011 00:00

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)
 ...

Posted by Community Admin on 07-Jun-2011 00:00

PS: Surely exposing the Categories in something like a usable interface has got to be on the wish list?!

Posted by Community Admin on 07-Jun-2011 00:00

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.

Posted by Community Admin on 07-Jun-2011 00:00

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

This thread is closed