LINQ查询表达式---------where子句

where 子句用在查询表达式中,用于指定将在查询表达式中返回数据源中的哪些元素。 它将一个布尔条件(“谓词”)应用于每个源元素(由范围变量引用),并返回满足指定条件的元素。 一个查询表达式可以包含多个 where 子句,一个子句可以包含多个谓词子表达式。

1.1 常见的where子句查询

static void Main(string[] args)
{
int[] numbers = { , , , , , , , , , }; var num1 = from n in numbers
where n >
select n; foreach (var i in num1)
{
Console.Write(i + " ");
} Console.Write("\n");
Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); var num2 = from n in numbers
where n >
where n % ==
select n; foreach (var i in num2)
{
Console.Write(i + " ");
} Console.Write("\n");
Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); var num3 = from n in numbers
where n > && n <
select n; foreach (var i in num3)
{
Console.Write(i + " ");
} Console.Write("\n");
Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); var num4 = from n in numbers
where (n == || n < ) && (n != )
select n; foreach (var i in num4)
{
Console.Write(i + " ");
} Console.ReadLine();
}
输出结果:
9 7 8 6
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
8 6
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7 8 6
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5 8 3 4 6 2 1 0

1.2 where子句中用自定义函数

static void Main(string[] args)
{
int[] numbers = { , , , , , , , , , }; var num = from n in numbers
where IsEva(n)
select n; foreach (var i in num)
{
Console.Write(i + " ");
} Console.ReadLine();
} public static bool IsEva(int i)
{
if (i % == )
return true;
else
return false;
}
查询结果:
8 4 6 2 0

1.3 动态微词的筛选

static void Main(string[] args)
{
int[] numbers = { , , , , , , , , , }; //定义动态的谓词数组,这个数组应该由实际运行环境生成
int[] number = { , , , , }; //查询在给定谓词数组里不存在的数字
var num = from n in numbers
where !number.Contains(n)
select n; foreach (var i in num)
{
Console.Write(i + " ");
} Console.ReadLine();
}
输出结果:
9 8 4 6 2

  

05-02 00:17