C语言 百分网手机站

c#查询关键字where 子句的运用

时间:2020-09-30 14:39:36 C语言 我要投稿

c#查询关键字where 子句的运用

  引导语:where是数据库中的一个指令,一般用于用于规定选择的标准。在c#中同样适用,以下是小编整理的c#查询关键字where 子句的运用,欢迎参考阅读!

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

  示例

  在下面的.示例中,where 子句筛选出除小于五的数字外的所有数字。如果移除 where 子句,则会返回数据源中的所有数字。表达式 num < 5 是应用于每个元素的谓词。

  C#

  class WhereSample

  {

  static void Main()

  {

  // Simple data source. Arrays support IEnumerable.

  int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

  // Simple query with one predicate in where clause.

  var queryLowNums =

  from num in numbers

  where num < 5

  select num;

  // Execute the query.

  foreach (var s in queryLowNums)

  {

  Console.Write(s.ToString() + " ");

  }

  }

  }

  //Output: 4 1 3 2 0

  在单一 where 子句内,可以使用 && 和 || 运算符根据需要指定任意多个谓词。在下面的示例中,查询将指定两个谓词,以便只选择小于五的偶数。

  C#

  class WhereSample2

  {

  static void Main()

  {

  // Data source.

  int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

  // Create the query with two predicates in where clause.

  var queryLowNums2 =

  from num in numbers

  where num < 5 && num % 2 == 0

  select num;

  // Execute the query

  foreach (var s in queryLowNums2)

  {

  Console.Write(s.ToString() + " ");

  }

  }

  }

  // Output: 4 2 0

  where 子句可以包含一个或多个返回布尔值的方法。在下面的示例中,where 子句使用一个方法来确定范围变量的当前值是偶数还是奇数。

  C# 

  class WhereSample3

  {

  static void Main()

  {

  // Data source

  int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

  // Create the query with a method call in the where clause.

  // Note: This won't work in LINQ to SQL unless you have a

  // stored procedure that is mapped to a method by this name.

  var queryEvenNums =

  from num in numbers

  where IsEven(num)

  select num;

  // Execute the query.

  foreach (var s in queryEvenNums)

  {

  Console.Write(s.ToString() + " ");

  }

  }

  // Method may be instance method or static method.

  static bool IsEven(int i)

  {

  return i % 2 == 0;

  }

  }

  //Output: 4 8 6 2 0

  备注

  where 子句是一种筛选机制。除了不能是第一个或最后一个子句外,它几乎可以放在查询表达式中的任何位置。where 子句可以出现在 group 子句的前面或后面,具体情况取决于是必须在对源元素进行分组之前还是之后来筛选源元素。

  如果指定的谓词对于数据源中的元素无效,则会发生编译时错误。这是 LINQ 提供的强类型检查的一个优点。

  编译时,where 关键字会被转换为对 Where 标准查询运算符方法的调用。

【c#查询关键字where 子句的运用】相关文章:

c#关键字查询之select 子句运用11-28

c#查询关键字之join 子句运用方法10-04

c#查询关键字from 子句的用法11-18

c#查询关键字之group子句的使用12-04

c#查询关键字之into的使用10-04

c#运算符关键字is的使用10-06

C# 术语大全10-19

浅谈C#语言的特点11-23

KMP算法的C#实现方法10-24