- 相關(guān)推薦
c#查詢關(guān)鍵字where 子句的運(yùn)用
引導(dǎo)語:where是數(shù)據(jù)庫中的一個(gè)指令,一般用于用于規(guī)定選擇的標(biāo)準(zhǔn)。在c#中同樣適用,以下是小編整理的c#查詢關(guān)鍵字where 子句的運(yùn)用,歡迎參考閱讀!
where 子句用在查詢表達(dá)式中,用于指定將在查詢表達(dá)式中返回?cái)?shù)據(jù)源中的哪些元素。它將一個(gè)布爾條件(“謂詞”)應(yīng)用于每個(gè)源元素(由范圍變量引用),并返回滿足指定條件的元素。一個(gè)查詢表達(dá)式可以包含多個(gè) where 子句,一個(gè)子句可以包含多個(gè)謂詞子表達(dá)式。
示例
在下面的示例中,where 子句篩選出除小于五的數(shù)字外的所有數(shù)字。如果移除 where 子句,則會(huì)返回?cái)?shù)據(jù)源中的所有數(shù)字。表達(dá)式 num < 5 是應(yīng)用于每個(gè)元素的謂詞。
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 子句內(nèi),可以使用 && 和 || 運(yùn)算符根據(jù)需要指定任意多個(gè)謂詞。在下面的示例中,查詢將指定兩個(gè)謂詞,以便只選擇小于五的偶數(shù)。
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 子句可以包含一個(gè)或多個(gè)返回布爾值的方法。在下面的示例中,where 子句使用一個(gè)方法來確定范圍變量的當(dāng)前值是偶數(shù)還是奇數(shù)。
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 子句是一種篩選機(jī)制。除了不能是第一個(gè)或最后一個(gè)子句外,它幾乎可以放在查詢表達(dá)式中的任何位置。where 子句可以出現(xiàn)在 group 子句的前面或后面,具體情況取決于是必須在對(duì)源元素進(jìn)行分組之前還是之后來篩選源元素。
如果指定的謂詞對(duì)于數(shù)據(jù)源中的元素?zé)o效,則會(huì)發(fā)生編譯時(shí)錯(cuò)誤。這是 LINQ 提供的強(qiáng)類型檢查的一個(gè)優(yōu)點(diǎn)。
編譯時(shí),where 關(guān)鍵字會(huì)被轉(zhuǎn)換為對(duì) Where 標(biāo)準(zhǔn)查詢運(yùn)算符方法的調(diào)用。
【c#查詢關(guān)鍵字where 子句的運(yùn)用】相關(guān)文章:
c#關(guān)鍵字查詢之select 子句運(yùn)用10-06
c#查詢關(guān)鍵字之join 子句運(yùn)用方法07-01
C# 術(shù)語大全07-29
c#快速排序算法10-21
c#冒泡排序算法08-15