More in this section

Forums / General Discussions / News - Filter by Category Linq expression

News - Filter by Category Linq expression

5 posts, 0 answered
  1. Paul
    Paul avatar
    24 posts
    Registered:
    16 May 2011
    07 Jun 2011
    Link to this post
    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
  2. Paul
    Paul avatar
    24 posts
    Registered:
    16 May 2011
    07 Jun 2011
    Link to this post
    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)
    {
     ...
    }
  3. Paul
    Paul avatar
    24 posts
    Registered:
    16 May 2011
    07 Jun 2011
    Link to this post
    PS: Surely exposing the Categories in something like a usable interface has got to be on the wish list?!
  4. SVA Webmaster
    SVA Webmaster avatar
    85 posts
    Registered:
    18 Jul 2007
    07 Jun 2011
    Link to this post
    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.
  5. Paul
    Paul avatar
    24 posts
    Registered:
    16 May 2011
    07 Jun 2011
    Link to this post
    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
5 posts, 0 answered