Pages

Monday, May 16, 2011

Optimized way to check if a dataset has any value

Working with datasets and we should make sure that object contains some data within.
Here is the optimized way to check if a dataset has any data within by using advanced .Net concepts like extension methods and Linq.

public static bool IsEmpty(this DataSet dataSet)
{
return dataSet == null || !(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any();
}

And we can use this extension method as follows:

DataSet dset = ... // Populate dataset by business method or logic
if (!dset.IsEmpty())
{
   ...
}

Extension methods provide a simple mechanism to extend types in the system (value, reference, and interface types) with new methods. These methods extend the original type and can be called like regular, defined instance methods, but they leave the original type and its methods untouched. Extension methods create the illusion that they are defined on a real type, but, in reality, no changes are made to the original types.

.NET Language-Integrated Query defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language.

No comments:

Post a Comment