Sitefinity Razor LINQ Sorting on Null PersistedValue from Choice Options

How do you sort a model in razor on Sitefinity widget templates using the choices option field from a dynamic module?

This one had me stump for a little while as persistedvalue doesn’t always exist on a new chioceoption field so you have to account for null values that could break the sort.

Here is the final solution and explanation:

LINQ Query
@foreach (var item in Model.Items.OrderBy(i => i.Fields.Year).ThenBy(i => i.Fields.Month == null ? 0 : Int32.Parse(i.Fields.Month.PersistedValue.ToString()) ))
{

}

Month is a choice option dropdown in the dynamic module.  The value of the option is 0-12.  I found that if I didn’t convert the persistedValue ToString the sort would throw an error, however converting to a string causes a sorting order problem because month 1 and months starting with one, 10, 11, 12 in alpha sort rank before 2,3,4.  Thus the int32.parse had to be added.

I handled the nulls by converting them to O.  Hence:  i => i.Fields.Month == null ? 0 : Int32.Parse(i.Fields.Month.PersistedValue.ToString())