Checking for empty EnumerableRowCollections when using LINQ
Posted
Thursday, April 24, 2008 10:18 AM
by
CoreyRoth
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.