The classic example of LINQ-where, select, selectiterator, and skipwhile clauses use array indexes.

Source: Internet
Author: User

Where clause usage

In addition to writing LINQ with a where clause, we can:

From P in products where P. unitsinstock> 0 & amp; p. unitprice & gt; 3.00 m select P;

You can also use the where extension method for objects in an array (all objects that implement the ienumerable interface.

 

Writing a query statement into multiple extension functions is actually a method for the compiler to process query statements, such as the following query statement:

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;

After compilation, the compiler generatesCodeIt is equivalent to the following code:

Iorderedsequence <int> M = arr. Where <int> (delegate (int n ){
Return (n <5 );
}). Orderby <int, int> (delegate (int n ){
Return N;
});

 

Here is an example of using the where extension method:

We have a string array of English words ranging from 0 to 9 at a time. We can query the English words whose length is smaller than the two digits in the array.

This query may be a bit difficult. You can check the following code first:

Public static void linqdemo01 ()
{
String [] digits = {"zero", "one", "two", "three", "four", "five", "Six", "Seven ", "Eight", "Nine "};
VaR vertex digits = digits. Where (DD, AA) => dd. Length <aa );
Console. writeline ("Short digits :");
Foreach (var d in each digits)
Console. writeline ("the word {0} is shorter than its value.", d );
}

Output result:

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.

 

Next we will analyze the core code in the above Code:

Digits. Where (DD, AA) => dd. Length <aa );

What have you caught in this line of code?

 

1. The WHERE clause is actually implemented using an extension method.

If you are not familiar with the extension method, first read my previous blogs:

Extension methods in C #3.0)

Use the Extension Method in C #3.0 to extend the interface

Orcas beta1 processing logic for multiple extension methods with the same name

The Extension function corresponding to the WHERE clause implemented by Microsoft is defined as follows:

Namespace system. LINQ
{
Public Delegate tresult func <targ0, targ1, tresult> (targ0 arg0, targ1 arg1 );
Public static class enumerable
{
Public static ienumerable <tsource> where <tsource> (this ienumerable <tsource> source, func <tsource, bool> predicate );
Public static ienumerable <tsource> where <tsource> (this ienumerable <tsource> source, func <tsource, Int, bool> predicate );
}
}

The Extension function in the red font is the extension function actually used in the above Code.

The Extension function parameter func <tsource, Int, bool> predicate defines the green delegate code of the above Code.

 

2. Where clause parameters are written in lambda expressions

If you do not know what lambda expressions are, you can refer to my previous blog:

C #3.0 lambda expressions (lambda expressions)

(DD, AA) => dd. Length <AA is equivalent to an anonymous function in C #2.0.

All the keywords in LINQ, such as select, selectmany, count, and all, are actually implemented using extension methods. The above usage also applies to these keyword clauses.

 

3. In this where clause, the second parameter of the lambda expression is the array index. We can use the array index inside the lambda expression. Make some complicated judgments.

In addition to the WHERE clause, the following select, selectdistinct, count, and all keywords with array Indexes

The following is an example.

 

Example of using an array index in a select clause

The following code has an integer array. We can find out if the number is the same as its position in this array.

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 );
}

Output result:

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

The extended function definition corresponding to the select clause, and the func <tsource, Int, tresult> delegate definition are as follows:

Public static ienumerable <tresult> select <tsource, tresult> (this ienumerable <tsource> source, func <tsource, Int, tresult> selector );

Public Delegate tresult func <targ0, targ1, tresult> (targ0 arg0, targ1 arg1 );

 

Example of selectmany clause using array Indexes

An array composed of several sentences. We want to split these sentences into words and display each word in that sentence. The query statement is as follows:

Public static void demo01 ()
{
String [] Text = {"Albert was here ",
"Burke slept late ",
"Connor is happy "};
VaR TT = text. selectcenters (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 );
}

Result:

ALBERT: 0
Was: 0
Here: 0
BURKE: 1
Slept: 1
Late: 1
CONNOR: 2
Is: 2
HAPPY: 2

 

Example of using array indexes in the skipwhile clause

Skipwhile means that the data is skipped until the expression items are satisfied, and the data is returned. no matter whether the subsequent items still meet the expression, note that it is different from where, where is returned only when the condition is met. skipwhile is used to find a record that meets the condition, and then all the subsequent data is returned.

In the following example, an integer array is returned, which is greater than or equal to the first position and subsequent data in the array.

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 );
}

Output result:

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

 

First, firstordefault, any, all, and count clauses

Note:

101 The first-indexed, firstordefault-indexed, any-indexed, all-indexed, and count-indexed examples in LINQ samples are no longer available in orcas beta1, that is, the following code is incorrect.

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 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 ddevenmatches = 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 );
}

To implement this function, you can use the WHERE clause as follows:

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 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 ddevenmatches = 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 );
}

References:

101 LINQ Samples

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.