配列やコレクションやIEnumerableなどの汎用 IsNullOrEmpty
id:siokoshou:20071208 の LINQ の限定子に重要なもの一つ追加。
Any() ってシーケンスに要素が含まれているかどうかどうかチェックする演算子でした。
Console.WriteLine( new int[] {}.Any() ); // false Console.WriteLine( new int[] { 1 }.Any() ); // true
名前からわからんよw
配列やコレクションでは null 使うなとは言うけれど、初期値が null だけに現実には混じってしまうんですよね…。そんなときに null を渡すと例外じゃ困るので IsNullOrEmpty を書いてみました。これは便利かも。バグや改良案があればコメントください。
using System; using System.Collections; using System.Collections.Generic; public static class Lib { public static bool IsNullOrEmpty( this IEnumerable source ) { //Console.Write( "x " ); // どっちが呼ばれた? if ( source == null ) return true; return source.Cast<object>().IsNullOrEmpty(); } public static bool IsNullOrEmpty<T>( this IEnumerable<T> source ) { if ( source == null ) return true; return !source.Any(); } }
使ってみる。
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace IsNullOrEmpty { class Program { static void Main() { int[] array0 = null; int[] array1 = { }; int[] array2 = { 1 }; int[] array3 = { 1, 2, }; Console.WriteLine( array0.IsNullOrEmpty() ); Console.WriteLine( array1.IsNullOrEmpty() ); Console.WriteLine( array2.IsNullOrEmpty() ); Console.WriteLine( array3.IsNullOrEmpty() ); Console.WriteLine(); var list0 = null as ArrayList; var list1 = new ArrayList() { }; var list2 = new ArrayList() { 1 }; var list3 = new ArrayList() { 1, 2 }; Console.WriteLine( list0.IsNullOrEmpty() ); Console.WriteLine( list1.IsNullOrEmpty() ); Console.WriteLine( list2.IsNullOrEmpty() ); Console.WriteLine( list3.IsNullOrEmpty() ); Console.WriteLine(); var dic0 = null as Dictionary<string, int>; var dic1 = new Dictionary<string, int> { }; var dic2 = new Dictionary<string, int> { { "a", 1 } }; var dic3 = new Dictionary<string, int> { { "a", 1 }, { "b", 2 } }; Console.WriteLine( dic0.IsNullOrEmpty() ); Console.WriteLine( dic1.IsNullOrEmpty() ); Console.WriteLine( dic2.IsNullOrEmpty() ); Console.WriteLine( dic3.IsNullOrEmpty() ); Console.WriteLine(); Console.WriteLine( Enumerable.Empty<double>().IsNullOrEmpty() ); Console.WriteLine( Enumerable.Range( 0, 0 ).IsNullOrEmpty() ); Console.WriteLine( Enumerable.Range( 0, 1 ).IsNullOrEmpty() ); Console.WriteLine( Enumerable.Range( 0, 2 ).IsNullOrEmpty() ); Console.ReadKey(); } } }
ちゃんと動きました。
# そういえば string.IsNullOrEmpty のコンパイラのバグはどうなったんだろ