LINQ Study Notes (2)

Source: Internet
Author: User

The following describes some query examples:

1. LINQ Query

VaR racers = from R in formula1.getchampions ()
Where R. Wins> 15 & (R. Country = "Brazil" | r. Country = "Austria") Select R;
Foreach (var r in racers)
{
Responose. Write ("{0: A}", R );
}

Query using extended Methods

Not all queries can be completed by using LINQ. Not all extension methods are mapped to the LINQ query clause. Extended methods are required for advanced queries. To better understand complex queries with extended methods, it is best to see how simple queries map. Using the extension methods where () and select () generates results that are very similar to those of the previous LINQ query:

VaR racers = formula1.getchampions (). where (r => r. wins> 15 & (R. country = "Brazil" | r. country = "Austria ")). select (r => r );

2. Use indexes for filtering

One example that cannot be queried using LINQ is the overload of the where () method. In the overload of the where () method, you can transmit the second parameter-index. The index is the counter of each result returned by the filter. You can use this index in the expression to perform index-based calculation. The followingCodeCalled by the where () extension method. It returns a contestant whose last name starts with a and whose index is an even number using the index:

VaR racers = formula1.getchampions (). Where (R, index) => r. lastname. startswith ("")&&

Index % 2! = 0 );
Foreach (var r in racers)
{
Responose. Write ("{0: A}", R );

}

3. Type Filter

To perform type-based filtering, you can use the oftype () Extension Method. Here, the array data contains string and INT objects. If you use the oftype () Extension Method to send the string class to the generic parameter, the string is returned from the set.

Object [] DATA = {"one", 2, 3, "four", "five", 6 };
VaR query = data. oftype <string> ();
Foreach (VAR s in query)
{
Console. writeline (s );
}

4. Composite from clause

VaR ferraridrivers = from R in formula1.getchampions () from C in R. cars where c = "Ferrari"
Orderby R. lastname select R. firstname + "" + R. lastname;

C # The Compiler converts the composite from clause and LINQ query to the selectmany () Extension Method. Selectsequence () can be used for the sequence of iterative sequences. In the example, the version of the selectmany () method is reloaded as follows:

Public static ienumerable <tresult> selectult <tsource, tcollection, tresult> (this ienumerable <tsource> source, func <tsource, ienumerable <tcollection> collectionselector, func <tsource, tcollection, tresult> resultselector );

The first parameter is an implicit parameter that receives the racer object sequence from the getchampions () method. The second parameter is the collectionselector delegate, which defines the internal sequence. In the lambda expression r => r. Cars, the racing set should be returned. The third parameter is a delegate, which is now called for each racing car to receive racer and car objects. Lambda expressions create an anonymous type with racer and car attributes. The result of this selectmany () method is to flatten the hierarchy of the players and racing cars and return an anonymous new object set for each racing car.

This new set is sent to the where () method to filter out players driving Ferrari. Finally, call the orderby () and select () methods:
VaR ferraridrivers = formula1.getchampions (). selectmany (r => r. cars,
(R, c) => New {racer = r, car = c }). where (r => r. car = "Ferrari "). orderby (r => r. racer. lastname ). select (r => r. racer. firstname + "" + R. racer. lastname );
Resolve the selectmany () generic method to the type used here. The parsed type is as follows. In this example, the data source is
The racer type. The filtered set is a string array. Of course, the name of the returned anonymous type is unknown. It is shown as tresult:
Public static ienumerable <tresult> selectult <racer, String, tresult> (
This ienumerable <racer> source, func <racer, ienumerable <string> collectionselector,
Func <racer, String, tresult> resultselector );
The query is only converted from a LINQ query to an extension method, so the result is the same as the previous one.

5. Sort

VaR racers = from R in formula1.getchampions () Where R. Country = "Brazil" orderby R. Wins descending select R;

The orderby clause is parsed as the orderby () method, and the orderby descending clause is parsed as the orderby descending () method:

VaR racers = formula1.getchampions (). Where (r => r. Country = "Brazil"). orderbydescending (r => r. Wins). Select (r => r );

The orderby () and orderbydescending () Methods return iorderenumerable <tsource>. This interface is derived from the ienumerable <tsource> interface, but contains an additional createorderedenumerable-<tsource> () method (). This method is used to further sort the sequence. If the two items are sorted by the keyword selector in the same order, you can use the thenby () and thenbydescending () Methods to continue sorting. The two methods require iorderenumerable <tsource> to work, but this interface is also returned. Therefore, you can add any number of thenby () and thenbydescending () Methods to sort the set.

When using a LINQ query, you only need to add all the different keywords used for sorting (separated by commas) to the orderby clause, for example

VaR racers = (from R in formula1.getchampions () orderby R. Country, R. lastname, R. firstname select R). Take (10 );

6. Group

VaR countries = from R in formula1.getchampions () group R by R. country into G orderby G. count () descending, G. key where G. count ()> = 2 select new {Country = G. key, Count = G. count ()};
Foreach (VAR item in countries)
{
Response. Write ("{0,-10} {1}", item. Country, item. Count );
}

Group representation of the extension method:

VaR countries = formula1.getchampions (). groupby (r => r. Country). orderbydescending (G => G. Count ()).
Thenby (G => G. key ). where (G => G. count ()> = 2 ). select (G => New {Country = G. key, Count = G. count ()});

7. Grouping nested objects

If the group object should contain nested objects, you can change the anonymous type created by the Select clause.

VaR countries = from R in formula1.getchampions () group R by R. Country into G orderby G. Count () descending, G. Key where G. Count ()> = 2 select new
{
Country = G. Key, Count = G. Count (),

Racers = from R1 in G orderby r1.lastname select r1.firstname + "" + r1.lastname
};
Foreach (VAR item in countries)
{
Response. Write ("{0,-10} {1}", item. Country, item. Count );
Foreach (VAR name in item. Racers)
{
Response. Write ("{0};", name );
}
Response. Write ("<br/> ");
}

8. Connection

You can use the join clause to merge two data sources according to specific conditions, but you must obtain the list of the two data sources to be connected.

VaR racers = from R in formula1.getchampions () from Y in R. years where Y> 2003 select new
{
Year = Y,
Name = R. firstname + "" + R. lastname
};

VaR teams = from T in formula1.getcontructorchampions () from Y in T. years where Y> 2003

Select New {year = Y, name = T. name };

With these two queries, join t in teams on R. year equals T. Year in the clause to obtain the result set.

VaR racersandteams = from R in racers join t in teams on R. year equals T. year select new
{
Year = R. Year,
Racer = R. Name,
TEAM = T. Name
};
Response. Write ("year champion" + "constructor title ");
Foreach (VAR item in racersandteams)
{
Response. Write ("{0 }:{ 1,-20} {2}", item. Year, item. racer, item. Team );
}

9. Set operation

The extension methods distinct (), Union (), intersect (), and except T () are both set operations.

VaR ferraridrivers = from R in formula1.getchampions () from C in R. cars where c = "Ferrari"
Orderby R. lastname select R;
Now another identical query is created, but the WHERE clause parameters are different to win the championship for all driving McLaren. It is best not to write the same query again. You can create a method to transmit the parameter car:
Private Static ienumerable <racer> getracersbycar (string car)
{
Return from R in formula1.getchampions () from C in R. cars where c = car orderby R. lastname select R;
}
However, because this method does not need to be used elsewhere, you should define a delegate type variable to save the LINQ query. The variable racerbycar must be a delegate type. It requires a string parameter and returns ienumerable <racer>, similar to the method previously implemented. Therefore, several generic delegation func <> are defined, so you do not need to declare your own delegation. Assign a Lambda expression to the variable racerbycar. A car variable is defined on the left of the lambda expression. Its type is the first generic parameter (string) Entrusted by func ). The LINQ query is defined on the right. It uses this parameter and the where clause:
Func <string, ienumerable <racer> racersbycar => from R in formula1.getchampions () from C in R. cars where c = car orderby R. lastname select R;
Now you can use the Intersect () Extension Method to win all the driving champions of Ferrari and McLaren:
Response. Write ("World Champion with" + "Ferrari and McLaren ");
Foreach (VAR racer in racersbycar ("Ferrari ").
Intersect (racersbycar ("McLaren ")))
{
Response. Write (racer );
}

10. Partition

Partitioning operations such as take () and skip () can be used for paging, for example, displaying 5x5 players. In the following LINQ query, the extension methods take () and skip () are added to the end of the query. The Skip () method first ignores the number of items calculated based on the page size and the actual number of pages, and then uses the take () method to extract a certain number of items based on the page size:
Int pagesize = 5;
Int numberpages = (INT) math. Ceiling (formula1.getchampions (). Count ()/(double) pagesize );

For (INT page = 0; page <numberpages; Page ++)
{
Response. Write ("Page {0}", page );
VaR racers = (from R in formula1.getchampions () orderby R. lastname select R. firstname + "" + R. lastname). Skip (page * pagesize). Take (pagesize );
Foreach (VAR name in racers)
{
Response. Write (name );
}
Response. Write ();
}

11. Total operator

Total operators such as Count (), sum (), min (), max (), average (), and aggregate () do not return a sequence, but return
Return a value.

VaR query = from R in formula1.getchampions () Where R. Years. Count ()> 3 orderby R. Years. Count () descending select new
{
Name = R. firstname + "" + R. lastname,
Timeschampion = R. Years. Count ()
};
Foreach (var r in query)
{
Response. Write ("{0} {1}", R. Name, R. timeschampion );
}

The sum () method summarizes all numbers in the sequence and returns the sum of these numbers. The sum () below is used to calculate the number
Total times. First, assign the WINS attribute to a certain country to win the competition in the newly created anonymous type.
Times.

VaR countries = (from C in from R in formula1.getchampions () group R by R. Country into C

Select New
{
Country = C. Key,
Wins = (from R1 in C select r1.wins). sum ()
}
Orderby C. Wins descending, C. Country select c). Take (5 );
Foreach (VAR country in countries)
{
Response. Write ("{0} {1}", country. Country, country. Wins );
}

The Methods min (), max (), average (), and aggregate () are used in the same way as Count () and sum. Min () returns a set
Returns the maximum value in the set. Average () calculates the average value in the set. For the aggregate () method, you can
To send a Lambda expression to summarize all values.

12. Conversion

The query can be postponed until the data item is accessed. Query is used in iteration, and the query is executed. Using the conversion operator will immediately execute the query and put the results in an array, list, or dictionary. In the following example, call the tolist () Extension Method, execute the query immediately, and put the result in list <t>:

List <racer> racers = (from R in formula1.getchampions ()
Where R. Starts> 150 orderby R. Starts descending select R). tolist ();
Foreach (VAR racer in racers)
{
Response. Write ("{0} {0: s}", Racer );
}

Putting the returned object in the list is not that easy. For example, you can use the new class lookup <tkey, telement> for fast access from a racing car to a contestant in a collection.

Tip:
Dictionary <tkey, tvalue> only one key corresponds to one value. Lookup <tkey,
In telement>, a key can correspond to multiple values. For more information about these types, see Chapter 1.
Using a composite from query, You can flat the competition operator and racing car sequence and create an anonymous type with the car and racer attributes. In the returned lookup object, the key type should be a string representing the car, and the value type should be a racer. To make this selection, you can send a key and an element selector to an overloaded version of The tolookup () method. The key selector represents the car attribute, and the element selector represents the racer attribute.

ILookup <string, Racer> racers = (from R in formula1.getchampions () from C in R. Cars select new
{Car = C, Racer = r}). tolookup (Cr => Cr. Car, Cr => Cr. Racer );
If (racers. Contains ("Williams "))
{
Foreach (VAR William amsracer in racers ["Williams"])
{
Response. Write (William sracer );
}
}

You can use the cast () method to query an untyped set by using LINQ, for example, arraylist. In the following example, the arraylist set based on the object type is filled with a racer object. To define a strongly typed query, you can use the cast () method.
System. Collections. arraylist list = new system. Collections. arraylist (formula1.getchampions ()
System. Collections. icollection );
VaR query = from R in list. Cast <racer> () Where R. Country = "USA" orderby R. Wins descending select R;
Foreach (VAR racer in query)
{
Response. Write ("{0: A}", Racer );
}

13. Generate Operators

The generate operators range (), empty (), and Repear () are not extension methods, but normal static methods of the returned sequence. In linqto objects, these methods can be used in the enumerable class. Sometimes you need to fill in the number of a range, then you should use the range () method. This method uses the first parameter as the starting value and the second parameter as the number of items to be filled.
VaR values = enumerable. Range (1, 20 );
Foreach (VAR item in values)
{
Response. Write ("{0}", item );
}
The range () method does not return a set filled with the defined values. Like other methods, this method also delays query execution and returns a rangeenumerator, with only one yield return statement, to increase the value. You can combine the result with other extension methods to obtain another result, for example, using the select () Extension Method:
VaR values = enumerable. Range (1, 20). Select (n => N * 3 );
The empty () method returns an iterator that does not return values. It can be used for parameters that require a set and can be used to transmit null sets to parameters.
. The repeat () method returns an iterator that repeat a specific number of times for the same value.

 

 

ASP. NET development technology exchange group:67511751(Recruitment ...)

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.