限定操作符运算返回一个Boolean值,该值指示序列中是否有一些元素满足条件或者是否所有元素都满足条件。
一、All操作符All方法用来确定是否序列中的所有元素都满足条件。看下面的例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LimitOperation
{
class Program
{
static void Main(string[] args)
{
string[] source1 = new string[] { "A", "B", "C", "D", "E", "F" };
string[] source2 = new string[] { "A", "A", "A", "A", "A", "A" };
Console.WriteLine(source1.All(w => w == "A")); //输出"False"
Console.WriteLine(source2.All(w => w == "A")); //输出 "True"
Console.ReadKey();
}
}
}
结果:
二、Any操作符先来看看Any的定义:
从定义中可以看出:Any有两个重载方法。Any方法的无参方式用来确定序列是否包含任何元素。Any方法的有参方式用来确定序列中是否有元素满足条件。只要有一个元素符合指定条件即返回true,如果一个符合指定条件的元素都没有则返回false。看下面的例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LimitOperation
{
class Program
{
static void Main(string[] args)
{
string[] source1 = new string[] { "A", "B", "C", "D", "E", "F" };
string[] source2 = new string[] { "A", "A", "A", "A", "A", "A" };
Console.WriteLine(source1.Any()); // 输出"True"
Console.WriteLine(source1.Any(w => w == "A")); //输出 "True"
Console.WriteLine(source2.Any(w => w == "G")); //输出 "False"
Console.ReadKey();
}
}
}
结果:
三、Contains操作符Contains方法用来确定序列是否包含满足指定条件的元素。如果有返回true,否则返回false。看下面的例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LimitOperation
{
class Program
{
static void Main(string[] args)
{
string[] source1 = new string[] { "A", "B", "C", "D", "E", "F" };
Console.WriteLine(source1.Contains("A")); //输出 "True"
Console.WriteLine(source1.Contains("G")); //输出 "False"
Console.ReadKey();
}
}
}
结果:
Contains还有另外一个重载的方法,看定义:
public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer);
该重载方法的参数是一个实现IEqualityComparer<TSource>接口的类型。看下面的例子。
定义实现IEqualityComparer<TSource>接口的类型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LimitOperation
{
/// <summary>
/// EqualityComparerEquals类实现IEqualityComparer接口
/// </summary>
public class EqualityComparerEquals : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return x == y;
}
public int GetHashCode(string obj)
{
return obj.ToString().GetHashCode();
}
}
}
方法中调用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LimitOperation
{
class Program
{
static void Main(string[] args)
{
string[] source1 = new string[] { "A", "B", "C", "D", "E", "F" };
var comparer = source1.Contains("F", new EqualityComparerEquals());
Console.WriteLine(comparer); //输出"True"
Console.ReadKey();
}
}
}
结果:
注意:在自定义的类中,x相当于数组中的每一个元素,y是要比较的元素:F。