Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save csdear/01215353ff3fef7fc4fc8ff5217e6631 to your computer and use it in GitHub Desktop.
Save csdear/01215353ff3fef7fc4fc8ff5217e6631 to your computer and use it in GitHub Desktop.
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment