How to convert from blocklistItem?
# help-with-umbraco
t
Hi all In my blocklist, I have an element called customers with a few fields. I try to get them like this var custs = page.Customers.OrderBy(x=> x.Content.getproperty('name') But this doesn't look good. How can I convert X in my order to a proper type/Customer without having to hard code a string into it? Thank you
j
I think you want something like
var custs = page.Customers.Select(x=> x.Content as Customer).OrderBy(c => c.Name)
That'll also give you a list of Customers, for use when you need them
t
Maybe I'm doing something wrong but this provides the error that it can't convert to a blocklistmodel?
j
What type is
Customers
?
t
Blocklist
j
I mean what c# type is the property in your code? If it is a blockList it should be of the type Umbraco.Cms.Core.Models.Blocks.BlockListModel
t
Intellisense shows me this as iorderedEnumerable but when I add the convert as above then blocklistitem changed from blocklistItem to Customer. Then I get the error
j
If
x.Content
inside your select is of the type
IPublishedElement
, and
Customer
inherits from
PublishedElementModel
then it should be able to cast it. If it cannot then you may have other blocks within the blocklist that are not of the type
Customer
You can do something like this:
Copy code
csharp
var custs = page.Customers.Select(x=> x.Content).OfType<Customer>().OrderBy(c => c.Name);
To get around the unsafe cast issue
t
That got me to the next step but now the code var items = new blocklistModel(custs); Breaks with unable to cast string 'name' to blocklistitem
j
That line doesn't really make sense, no reason to create a new blocklistmodel, what are you trying to do with these customer models?
t
It's some existing code someone else wrote. All it does is get the names of the customers in alphabetical order then displays it. A blocklistmodel is passed to the front facing view. All works but then I was asked to convert it to proper type and that's when it broke 😕
j
If you use
Copy code
csharp
var customers = page.Customers.Select(x=> x.Content).OfType<Customer>().OrderBy(c => c.Name);
Then
customers
are a list of Customers ordered by name. So you probably want to change the return type from BlockListModel to IEnumerable and then change the callers of the method to this instead