stuart-d2
8/25/2016 - 4:02 PM

Checking a Enumerable Collection Null and Handling with a Extension Method

Checking a Enumerable Collection Null and Handling with a Extension Method

//Ref: Vulcraft project, NewsReleaseArchive.cshtml and EnumExtensions.cs class

//1.  Implement the extenstion method. E.g., Helpers>>Extensions>>EnumExtensions.cs  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Vulcraft.Web.Helpers.Extensions
{
    public static class EnumExtensions
    {
        public static bool IsAny<T>(this IEnumerable<T> data)
        {
            return data != null && data.Any();
        }
    }
}

//2.  Example use, catching and handling nulls in a collection  

@model Vulcraft.Web.Models.ViewModels.News.NewsDetailViewModel
@using Vulcraft.Web.Helpers.Extensions
[...]
<div class="panel-body">
                    <ul>
                        @if (Model.NewsItems.IsAny())
                        { 
                            foreach (var newsrelease in Model.NewsItems)
                            {
                            
                                if (@newsrelease.NewsItemDate.Year == 2016)
                                {
                                    <li>@newsrelease.Title</li>
                                    <li>@newsrelease.NewsItemDate</li>
                                }
                            }
                        }
                        else
                        {
                            <li><i>No Headline Data Available</i></li>
                        }
                    </ul>
                </div>