欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C# Any()和AII()方法的區(qū)別

 更新時間:2022年06月29日 10:40:20   作者:biyusr  
本文主要介紹了C# Any()和AII()方法的區(qū)別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

我們常常需要的另一類查詢是確定數(shù)據(jù)是否滿足某個條件,或者確保所有數(shù)據(jù)都滿足某個條件。例如,需要確定某個產(chǎn)品是否已經(jīng)脫銷(庫存為 0),或者是否發(fā)生了某個交易。

LINQ 提供了兩個布爾方法:Any()和 All(),它們可以快速確定對于數(shù)據(jù)而言,某個條件是 true 還是 false。因此很容易地找到數(shù)據(jù),如下面的示例所示。

按照下面的步驟在Visual Studio 中創(chuàng)建示例:

(1)創(chuàng)建一個新的控制臺應用程序。

(2)創(chuàng)建 Customer 類的代碼和初始化顧客列表(List<Customer>customers)的代碼。

(3)在Main() 方法中,在 customers 列表初始化和查詢聲明后,刪除處理循環(huán),輸入如下所示的代碼:

bool anyUSA = customers.Any(c => c.Country == "USA"); 
if (anyUSA)
{
   Console.WriteLine("Some customers are in the USA");
}
else
{
   Console.WriteLine("No customers are in the USA");
}
bool allAsia = customers.All(c => c.Region == "Asia"); 
if (allAsia)
{
   Console.WriteLine("All customers are in Asia");
}
else
{
   Console.WriteLine("Not all customers are in Asia");
}

(4)編譯并執(zhí)行程序,將看到一些消息,指出一些顧客來自美國,并不是所有的顧客都來自亞洲:

Some customers are in the USA 
Not all customers are in Asia
Program finished, press Enter/Return to continue:

示例的說明

Customer 類和 customers 列表的初始化與前面例子中的相同。在第一個查詢語句中,調(diào)用了 Any() 方法,用一個簡單的 Lambda 表達式檢查 Customer Country 字段的值是不是USA:

bool anyUSA = customers.Any(c => c.Country == "USA");

LINQ方法Any() 把傳送給它的 Lambda 表達式 c=>c.Country=="USA"應用于customers 列表中的所有數(shù)據(jù),如果對于列表中的任意顧客,Lambda 表達式是 true,就返回 true。

接著檢查 Any() 方法返回的布爾結(jié)果變量,輸出一個消息,顯示查詢的結(jié)果 Any()方法雖然僅返回 true 或 false,但它會執(zhí)行一個查詢,得到 true 或 false 結(jié)果):???????

if (anyUSA)
{
   Console.WriteLine("Some customers are in the USA");
}
else
{
   Console.WriteLine("No customers are in the USA");
}

雖然可以通過一些巧妙的代碼使這個消息更緊湊一些,但這里的代碼比較直觀,便于理解。anyUSA 設為 true, 因為數(shù)據(jù)集中的確有顧客居住在美國,所以看到了消息 Some customers are in the USA.

在下一個查詢語句中,調(diào)用了 AII() 方法,利用另一個簡單的 Lambda 表達式確定是否所有的顧客都來自亞洲:

bool allAsia = customers.All(c=> c.Region =="Asia");

LINQ 方法All() 把 Lambda 表達式應用于數(shù)據(jù)集,并返回 false,因為有一些顧客不是來自亞洲。然后根據(jù) allAsia 的值返回相應的消息。

到此這篇關(guān)于C# Any()和AII()方法的區(qū)別的文章就介紹到這了,更多相關(guān)C# Any()和AII()內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論