Umbraco v9 Convert IEnumerable<IPublishedContent> search result (examine) to strongly typed models

526 Views Asked by At

I have created a ViewComponent, where it gets the search string parameter to search through Umbraco content. I have implemented the search and the possible results are of IEnumerable. This part is tested and it works.

The problem that I have is how to cast this IEnumerable into possibly more Backoffice models (ModelsBuilder C# classes)?

Another question, why doesn't Intellisense work with IPublishedContent?

enter image description here

Thanks for all the help!

1

There are 1 best solutions below

2
Robert Foster On

if you know the Document Type of the content coming from the search, and it's all the same results, you can use the following:

var content = results.OfType<Model>();

assuming results === IEnumerable<IPublishedContent>

But quite often the results you get back from a search consist of several different Document Types, in which case you can do something like this when rendering them out:

foreach(var result in results) {
  if (result is PageModel1 pageModel1) 
  {
    // render out the details for a `PageModel1` Document Type based on the
    // new variable pageModel1
  }
  else if (result is PageModel2 pageModel2) 
  {
    // render out the details for a `PageModel2` Document Type based on the
    // new variable pageModel1
  }