Any()
Any()
可以判断序列是否为空。
MSDN
public static bool Any<TSource>( this IEnumerable<TSource> source );
代码示例:
public static class Program
{
static void Main( string[] args )
{
int[] numbersA = new int[] { };
int[] numbersB = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
bool reaultA = numbersA.Any();
bool reaultB = numbersB.Any();
System.Console.WriteLine( "numbersA:{0}", numbersA.Text() );
System.Console.WriteLine( "numbersB:{0}", numbersB.Text() );
System.Console.WriteLine( "numbersA是否有元素:{0}", reaultA );
System.Console.WriteLine( "numbersB是否有元素:{0}", reaultB );
System.Console.ReadKey();
}
public static string Text<TSource>( this IEnumerable<TSource> i_source )
{
string text = string.Empty;
foreach( var value in i_source )
{
text += string.Format( "[{0}], ", value );
}
return text;
}
}
numbersA:
numbersB:[0], [1], [2], [3], [4], [5], [6], [7], [8], [9],
numbersA是否有元素:False
numbersB是否有元素:True
还可以用于检查是否有满足条件的元素。
MSDN
public static bool Any<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate );
以下示例描述了使用lambda表达式的条件语句。
代码示例:
public static class Program
{
static void Main( string[] args )
{
int[] numbers = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
bool reaultA = numbers.Any( value => value % 2 == 0 );
bool reaultB = numbers.Any( value => value >= 10 );
bool reaultC = numbers.Any( value => value < 5 );
System.Console.WriteLine( "numbers:{0}", numbers.Text() );
System.Console.WriteLine( "偶数 :{0}", reaultA );
System.Console.WriteLine( "大于等于10:{0}", reaultB );
System.Console.WriteLine( "小于5 :{0}", reaultC );
System.Console.ReadKey();
}
public static string Text<TSource>( this IEnumerable<TSource> i_source )
{
string text = string.Empty;
foreach( var value in i_source )
{
text += string.Format( "[{0}], ", value );
}
return text;
}
}
numbers:[0], [1], [2], [3], [4], [5], [6], [7], [8], [9],
偶数 :True
大于等于10:False
小于5 :True