c语言中的where用法,c#查询关键字where 子句的运用

本文详细介绍了C#查询关键字`where`子句的使用方法,它用于在查询表达式中筛选数据源中的元素。示例展示了如何通过where子句筛选出小于特定值的数字,以及如何结合&&和||运算符指定多个谓词。此外,还展示了在where子句中使用方法来判断元素属性的情况。`where`子句在查询表达式中的位置灵活,但不能作为第一个或最后一个子句。文章强调了where子句在提供强类型检查方面的优势。
摘要由CSDN通过智能技术生成

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 标准查询运算符方法的调用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值