in

Dot Net Mafia

Group site for developer blogs dealing with (usually) .NET, SharePoint 2013, SharePoint 2010, Office 365, SharePoint Online, and other Microsoft products, as well as some discussion of general programming related concepts.

This Blog

Syndication

Archives

Corey Roth [MVP]

A SharePoint MVP bringing you the latest time saving tips for SharePoint 2013, Office 365 / SharePoint Online and Visual Studio 2013.

Checking for empty EnumerableRowCollections when using LINQ

After you query something with LINQ, you may want to know if any results were returned before your start enumerating or working with the EnumerableRowCollection (that's most likely the type behind that var you are using in most cases).  Consider the following example.

DataTable myDataTable = new DataTable();

 

var queryResults = from queryResult in myDataTable.AsEnumerable()

                   where queryResult.Field<DateTime>("ItemDateTime") < DateTime.Now

                   select new

                   {

                       intColumn1 = queryResult.Field<int>("IntColumn1"),

                       stringColumn1 = queryResult.Field<string>("StringColun1")

                   };

At first you might try something like this.

if (queryResults != null)

However this will just tell you if the collection is null (and it seems that the collection always has some value regardless of the results of the query).  There are two ways that I can think of off the top of my head to check for this.  First, you can use the Count() method.

if (queryResults.Count() > 0)

If you don't like that, you can also use the more eloquent Any() method.  I've mentioned this method in the past as a way to check for nulls.  Any() can be used to check to see if just about anything exists including elements, attributes, and rows.  Here is what it looks like.

if (queryResults.Any())

{

    var result = queryResults.First();

 

    Console.WriteLine("Results: {0}", result.intColumn1);

}

The reason I bring this up is that, you have to check if something exists in the collection before calling the First() method.  Although, you really don't have to check to see if rows exists before enumerating this collection, you do have to use it before calling First() because it will throw an exception if no rows exist.  Btw, First() returns the first item in the EnumerableRowCollection if that wasn't obvious already.

Published Apr 24 2008, 10:18 AM by CoreyRoth
Filed under: ,

Comments

No Comments

Leave a Comment

(required)  
(optional)
(required)  
Add

About CoreyRoth

Corey Roth is an independent SharePoint consultant specializing in ECM, Apps, and Search.
2012 dotnetmafia.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems