返回LINQ大全首页
Any()Any()
可以判断序列是否为空。 MSDN public static bool Any( this IEnumerable 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( this IEnumerable 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( this IEnumerable source, Func 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
关注
打赏