Created
August 25, 2016 16:02
-
-
Save csdear/01215353ff3fef7fc4fc8ff5217e6631 to your computer and use it in GitHub Desktop.
Checking a Enumerable Collection Null and Handling with a Extension Method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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