[C #] C # learning notes-LINQ

Source: Internet
Author: User

C # Study Notes-LINQ

Luo chaohui (http://www.cnblogs.com/kesalin)

C # And. Net advancedProgramDesign Reading Notes

 

1. The intention of LINQ (Language-level integrated query) is to provide a unified and symmetric way for programmers to obtain and operate on data in a broad sense. By using LINQ, we can #Programming LanguageDirectly create an object called a query expression. These Query expressions are based on many query operators and intentionally designed to be similar to SQL expressions. However, they can be used to interact with multiple types of data, not limited to relational databases. Specifically, LINQ allows Query expressions to operate on any objects, relational databases, dataset, or XML documents that directly or indirectly implement the ienumerable <t> interface through extension methods in a unified manner.

 Static    Void Queryoverstring ()
{
String [] Games = { " Morrowind " , " Bioshock " , " Half Life 2 " , " The darkness " };

// Create a query expression to represent items with more than 6 letters in the array.
Ienumerable < String > Subset = Form GIn Games Where G. length> 6 Orderby G Select G;

// Output result
Foreach ( String S In Subset)
Console. writeline ( " Item: {0} " , S );
}

2. LINQ expressions are strongly typed and extensible. In the above example, the subset type is determined, even if we use VaR to modify it. Before the content is iterated, The LINQ expression does not actually perform operations. This feature is called delayed execution. The advantage of this feature is that it can apply the same LINQ query to the same container for multiple times, and always get the latest and best results. If you want to execute it immediately, you can call many extension methods defined by the enumerable type, such as toarray, todictionary, tkey, and tolist extension methods, they allow us to capture the results of the LINQ query with a strong type container.

3. the query operator of LINQ is designed for any type that implements the ienumerable <t> interface, whether directly or indirectly through the extension method. But system. in collections, traditional non-generic container classes do not have these structures. We can use generic enumerable. oftype <t> method to iterate the data contained in these non-generic sets. Because non-generic types can contain any type of items, we can use oftype <t> to filter elements of different types that need to be iterated.

Arraylist STRs = New Arraylist (){ "  One  " , " Two  " , "  Three  " };

// Converts an arraylist to a Type compatible with ienumerable <t>.
Ienumerable < String > Strenum = STRs. oftype < String > ();

// Create a query expression
VaR Longstr = From Str In STRs Where Str. length> 2 Select STR;

4. In the preceding example, the query operators (such as: from, in, where, orderby, and select) and the C # compiler translate these tags into the system. LINQ. call of various methods of the enumerable type (or other types, depending on the LINQ query ). In fact, the prototype of many methods of enumerable is to delegate the parameters of last night. In particular, many methods require a definition in system. core. in the DLL system namespace, the generic Delegate of the type func <> is used as a parameter. The delegate can accept up to four input parameters. We can manually create a new delegate type, write the required target method, and use the anonymous method of C #, or define a proper Lambda expression to replace the query expression. The preceding example can be rewritten:

Arraylist STRs = New Arraylist (){ " One  " , "  Two  " , "  Three  " };

// Converts an arraylist to a Type compatible with ienumerable <t>.
Ienumerable < String > Strenum = STRs. oftype < String > ();

// Create a query expression
VaR Longstr = STRs. Where (STR => Str. length> 2 ). Select (STR => Str );

Or

Arraylist STRs = New Arraylist (){ "  One  " , "  Two  " , "  Three " };

// Converts an arraylist to a Type compatible with ienumerable <t>.
Ienumerable < String > Strenum = STRs. oftype < String > ();

// Use the enumerable type and anonymous method to create a query expression
// Use the anonymous method to create the required func <> delegate
Func < String ,Bool > Filter = Delegate ( String Str ){ Return Str. length> 2 ;};
Func < String , String > Itemtoprocess = Delegate ( String S ){ Return S ;};

// Method for passing a delegate to enumerable
VaR Subset = STRs. Where (filter). Select (itemtoprocess );

5. The LINQ query operators include: from, in, where, select, join, on, equals, into, orderby, ascending, descending, group, and. In addition, the enumerable type also provides a set of simplified symbols without direct query operators, and is presented in an extension method, you can call these generic methods to convert a result set in various ways (such as reverse <> (), toarray <> (), tolist <> ); or perform operations (distinct <> (), Union <> (), Intersect <> () on the result set ); or aggregate the result set (count <> (), sum <> (), Min <> (), max <> ). For example:

//Retrieve the total number of queries
IntNumb = (FromStrInSTRsWhereStr. length>2). Count <String> ();

6. We can also project a new data form from an existing data source. The specific method is to define a SELECT statement and dynamically form a new type through the anonymous type.

 Class Car
{
Public String Petname = String . Empty;
Public String Color = String . Empty;
}

Car [] mycars = New [] {
New Car {petname = " Henry " , Color = " White " },
New Car {petname = " Daisy " , Color = " Tan " },
New Car {petname = " Mary " , Color = " Black " },
};

// Query subset
VaR Onlyblack = From C In Mycars Where C. Color = " Black " Select C;

// New Projection data type
VaR Names = From CIn Mycars Select New {C. petname };
Foreach ( VaR O In Names)
Console. writeline (O. petname );

There is a problem with the projection technology. We cannot regard the new data projected as the return value because it is an implicit type (VAR names ), because we must convert it to a strong data type (such as array) and then return it. If we want to return names in the previous example, we can use return names. toarray ().

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.