国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

LINQ的經(jīng)典例子-Where,Select、SelectMany、SkipWhile子句中使用數(shù)組索引

2019-11-17 03:58:26
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友
Where 子句的用法

我們除了可以如下方式書寫帶Where子句的LINQ外:

from p in PRoducts where p.UnitsInStock > 0 && p.UnitPrice > 3.00M select p;

還可以對(duì)數(shù)組(所有實(shí)現(xiàn)了IEnumerable接口的對(duì)象都可以)的實(shí)體使用 Where 擴(kuò)展方法。

把一個(gè)查詢語(yǔ)句寫成多個(gè)擴(kuò)展函數(shù)的方式,這其實(shí)是編譯器處理查詢語(yǔ)句的方法,比如下面的查詢語(yǔ)句:

int[] arr = new int[] { 8, 5, 89, 3, 56, 4, 1, 58 };
var m = from n in arr where n < 5 orderby n select n;

編譯器在編譯后,替我們產(chǎn)生的代碼等價(jià)于如下的代碼:

IOrderedSequence m = arr.Where(delegate (int n) {
    return (n < 5);
}).OrderBy(delegate (int n) {
    return n;
});

下面我們來(lái)看一個(gè)使用Where擴(kuò)展方法的例子:

我們有一個(gè)字符串?dāng)?shù)組,一次是0到9的英文單詞,我們查詢出這10個(gè)字符的長(zhǎng)度比它所在數(shù)組的位置 這兩個(gè)數(shù)字比較小的英文單詞.

這個(gè)查詢可能有些繞口,你可以先看下面這些代碼:

public static void LinqDemo01()
{
    string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
    var shortDigits = digits.Where((dd, aa) => dd.Length < aa);
    Console.WriteLine("Short digits:");
    foreach (var d in shortDigits)
        Console.WriteLine("The Word {0} is shorter than its value.", d);
}

輸出結(jié)果:

Short digits:
The word five is shorter than its value.
The word six is shorter than its value.
The word seven is shorter than its value.
The word eight is shorter than its value.
The word nine is shorter than its value.

下面我們就來(lái)分析上述代碼中最核心的代碼:

digits.Where((dd, aa) => dd.Length < aa);

這行代碼都趕了些什么?

1、Where子句其實(shí)是用擴(kuò)展方法來(lái)實(shí)現(xiàn)的

如果你對(duì)擴(kuò)展方法不熟悉,請(qǐng)先看我之前的幾篇博客:

C#3.0 中的擴(kuò)展方法 (Extension Methods)

C#3.0 中使用擴(kuò)展方法來(lái)擴(kuò)展接口

Orcas Beta1 對(duì)多個(gè)同名擴(kuò)展方法的處理邏輯

微軟替我們實(shí)現(xiàn)的 Where 子句對(duì)應(yīng)的擴(kuò)展函數(shù)實(shí)際是如下的定義:

namespace System.Linq
{
    public delegate TResult Func(TArg0 arg0, TArg1 arg1);
    public static class Enumerable
    {
        public static IEnumerable Where(this IEnumerable source, Func predicate);
        public static IEnumerable Where(this IEnumerable source, Func predicate);
    }
}

其中紅色字體的那個(gè)擴(kuò)展函數(shù),就是我們上面代碼實(shí)際使用的擴(kuò)展函數(shù)。

我們這個(gè)擴(kuò)展函數(shù)參數(shù):Func predicate 的定義看上面代碼的綠色delegate 代碼。

2、Where 子句參數(shù)書寫的是Lambda 表達(dá)式

如果你不清楚什么是Lambda 表達(dá)式,你可以參看我之前的博客:

C# 3.0 的Lambda表達(dá)式(Lambda Expressions)

(dd, aa) => dd.Length < aa 就相當(dāng)于 C# 2.0 的匿名函數(shù)。

LINQ中所有關(guān)鍵字比如 Select,SelectMany, Count, All 等等其實(shí)都是用擴(kuò)展方法來(lái)實(shí)現(xiàn)的。上面的用法同樣也適用于這些關(guān)鍵字子句。

3、這個(gè)Where子句中Lambda 表達(dá)式第二個(gè)參數(shù)是數(shù)組索引,我們可以在Lambda 表達(dá)式內(nèi)部使用數(shù)組索引。來(lái)做一些復(fù)雜的判斷。

具有數(shù)組索引的LINQ關(guān)鍵字除了Where還以下幾個(gè)Select,SelectMany, Count, All

我們下面就來(lái)依次舉例

Select 子句使用數(shù)組索引的例子

下面代碼有一個(gè)整數(shù)數(shù)組,我們找出這個(gè)數(shù)字是否跟他在這個(gè)數(shù)組的位置一樣

public static void LinqDemo01()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
    var numsInPlace = numbers.Select((num, index) => new { Num = num, InPlace = (num == index) });
    Console.WriteLine("Number: In-place?");
    foreach (var n in numsInPlace)
        Console.WriteLine("{0}: {1}", n.Num, n.InPlace);
}

輸出結(jié)果:

Number: In-place?
5: False
4: False
1: False
3: True
9: False
8: False
6: True
7: True
2: False
0: False

其中我們用到的這個(gè)Select子句對(duì)應(yīng)的擴(kuò)展函數(shù)定義,以及其中Func委托定義如下:

public static IEnumerable Select(this IEnumerable source, Func selector);

public delegate TResult Func(TArg0 arg0, TArg1 arg1);

SelectMany 子句使用數(shù)組索引的例子

幾個(gè)句子組成的數(shù)組,我們希望把這幾個(gè)句子拆分成單詞,并顯示每個(gè)單詞在那個(gè)句子中。查詢語(yǔ)句如下:

public static void Demo01()
{
    string[] text = { "Albert was here",
          "Burke slept late",
          "Connor is happy" };
    var tt = text.SelectMany((s, index) => from ss in s.Split(' ') select new { Word = ss, Index = index });
    foreach (var n in tt)
        Console.WriteLine("{0}:{1}", n.Word,n.Index);
}

結(jié)果:

Albert:0
was:0
here:0
Burke:1
slept:1
late:1
Connor:2
is:2
happy:2

SkipWhile 子句使用數(shù)組索引的例子

SkipWhile 意思是一直跳過(guò)數(shù)據(jù),一直到滿足表達(dá)式的項(xiàng)時(shí),才開始返回?cái)?shù)據(jù),而不管之后的項(xiàng)是否仍然滿足表達(dá)式,需要注意他跟Where是不一樣的,Where是滿足條件的記錄才返回,SkipWhile 是找到一個(gè)滿足條件的,然后后面的數(shù)據(jù)全部返回。

下面例子返回一個(gè)整數(shù)數(shù)組中,這個(gè)整數(shù)比他自身在這個(gè)數(shù)組的位置大于等于的第一個(gè)位置以及之后的數(shù)據(jù)。

public static void Linq27()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
    var laterNumbers = numbers.SkipWhile((n, index) => n >= index);
    Console.WriteLine("All elements starting from first element less than its position:");
    foreach (var n in laterNumbers)
        Console.WriteLine(n);
}

輸出結(jié)果:

All elements starting from first element less than its position:
1
3
9
8
6
7
2
0

First 、FirstOrDefault、Any、All、Count 子句

注意:

101 LINQ Samples  中 First - Indexed、FirstOrDefault - Indexed、 Any - Indexed、All - Indexed、Count - Indexed 這五個(gè)例子在 Orcas Beta1中已經(jīng)不在可用,即下面代碼是錯(cuò)誤的。

public void Linq60() {
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
    int evenNum = numbers.First((num, index) => (num % 2 == 0) && (index % 2 == 0));
    Console.WriteLine("{0} is an even number at an even position within the list.", evenNum);
}

public void Linq63() {
    double?[] doubles = { 1.7, 2.3, 4.1, 1.9, 2.9 };
    double? num = doubles.FirstOrDefault((n, index) => (n >= index - 0.5 && n <= index + 0.5));
    if (num != null)
        Console.WriteLine("The value {1} is within 0.5 of its index position.", num);
    else
        Console.WriteLine("There is no number within 0.5 of its index position.", num);
}

public void Linq68() {
   int[] numbers = { -9, -4, -8, -3, -5, -2, -1, -6, -7 };
   bool negativeMatch = numbers.Any((n, index) => n == -index);
   Console.WriteLine("There is a number that is the negative of its index: {0}", negativeMatch);
}

public void Linq71() {
   int[] lowNumbers = { 1, 11, 3, 19, 41, 65, 19 };
   int[] highNumbers = { 7, 19, 42, 22, 45, 79, 24 };
   bool allLower = lowNumbers.All((num, index) => num < highNumbers[index]);
   Console.WriteLine("Each number in the first list is lower than its counterpart in the second list: {0}", allLower);
}

public void Linq75() {
   int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
   int oddEvenMatches = numbers.Count((n, index) => n % 2 == index % 2);
   Console.WriteLine("There are {0} numbers in the list whose odd/even status " +
        "matches that of their position.", oddEvenMatches);
}

要實(shí)現(xiàn)這個(gè)功能,可以用Where 子句,如下:

public static void Linq60()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
    int evenNum = numbers.Where((num,index) =>( num % 2 == 0 && index %2 == 0) ).First();
    Console.WriteLine("{0} is an even number at an even position within the list.", evenNum);
}

public static void Linq63()
{
    double?[] doubles = { 1.7, 2.3, 4.1, 1.9, 2.9 };
    double? num = doubles.Where((n, index) => (n >= index - 0.5 && n <= index + 0.5)).FirstOrDefault();
    if (num != null)
        Console.WriteLine("The value {1} is within 0.5 of its index position.", num);
    else
        Console.WriteLine("There is no number within 0.5 of its index position.", num);
}

public static void Linq68()
{
    int[] numbers = { -9, -4, -8, -3, -5, -2, -1, -6, -7 };
    bool negativeMatch = numbers.Where((n, index) => n == -index).Any();
    Console.WriteLine("There is a number that is the negative of its index: {0}", negativeMatch);
}

public static void Linq71()
{
    int[] lowNumbers = { 1, 11, 3, 19, 41, 65, 19 };
    int[] highNumbers = { 7, 19, 42, 22, 45, 79, 24 };
    bool allLower = lowNumbers.Where((num, index) => num < highNumbers[index]).All(n => true);
    Console.WriteLine("Each number in the first list is lower than its counterpart in the second list: {0}", allLower);
}

public static void Linq75()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
    int oddEvenMatches = numbers.Where((n, index) => n % 2 == index % 2).Count();
    Console.WriteLine("There are {0} numbers in the list whose odd/even status " +
         "matches that of their position.", oddEvenMatches);
}

參考資料:



本文來(lái)自CSDN博客,轉(zhuǎn)載請(qǐng)標(biāo)明出處:http://blog.csdn.net/dz45693/archive/2009/12/17/5028035.aspx
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 望奎县| 玛纳斯县| 嵊泗县| 清徐县| 罗平县| 东莞市| 高尔夫| 手游| 枣强县| 新干县| 大田县| 临江市| 高要市| 株洲市| 纳雍县| 通许县| 广灵县| 民县| 阜平县| 许昌市| 深圳市| 灌云县| 麻栗坡县| 肇源县| 丹寨县| 新营市| 翁牛特旗| 资兴市| 改则县| 宜城市| 滨海县| 通道| 神木县| 会泽县| 阜阳市| 桓仁| 南平市| 高密市| 阿坝县| 葫芦岛市| 荆门市|