Architect's Log

I'm a Cloud Architect. I'm highly motivated to reduce toils with driving DevOps.

DataTableがNullまたは空かどうかを判定する拡張メソッドを定義する

DataTableがNullまたは空かどうかを判定する拡張メソッドを定義します。DataRowを保持していない場合に空と判断しています。
System.ComponentModel.IListSourceを実装したインスタンスであれば、DataTable以外でも使えます。

Extensions.cs

using System.ComponentModel;

namespace Extensions {
    public static class SystemComponentModelExtensions {
        /// <summary>
        /// 指定されたインスタンスがNullまたは要素数が0かどうかを示す値を取得します。
        /// </summary>
        /// <param name="self">IListSourceのインスタンス。</param>
        /// <returns>Nullまたは要素数が0の場合はtrue。それ以外の場合はfalse。</returns>
        public static bool IsNullOrEmpty(this IListSource self) {
            return (self == null) || (self.GetList().Count == 0);
        }
    }
}

Program.cs

using System;
using System.Data;
using Extensions;

namespace ConsoleApplication {
    class Program {
        static void Main(string[] args) {
            // Null
            DataTable dt = null;
            Console.WriteLine(dt.IsNullOrEmpty());

            // 行なし
            dt = new DataTable();
            dt.Columns.Add("col1", typeof(string));
            dt.Columns.Add("col2", typeof(string));
            dt.Columns.Add("col3", typeof(string));
            Console.WriteLine(dt.IsNullOrEmpty());

            // 行あり
            dt.Rows.Add("a", "b", "c");
            Console.WriteLine(dt.IsNullOrEmpty());

            Console.ReadLine();
        }
    }
}

実行結果