[. Net Object-Oriented Programming Basics] (19) Basics of LINQ and Object-Oriented Programming
[. Net Object-Oriented Programming Basics] (19) Basics of LINQ
In the last two sections, we introduced. net arrays, collections, and generics. We have mentioned that arrays are a reference type extended from the previous programming language and are allocated by pre-defined length. The set is. in the early stage of the Net version, it was designed to solve the problem of convenient dataset retrieval. In addition to the convenience of retrieval, it can also automatically allocate storage areas during use without the need to define the size in advance. However, the set has performance problems caused by unsafe types and frequent packing and unpacking operations. The generic model is designed to solve the defects of the set after. net 2.0. It adopts the method of declaring the type again in the instance call phase, which solves the security problem and the efficiency problem.
With the development of. net 3.5 and later versions, Microsoft has designed LINQ to make it easier for us to search and develop more efficiently.
1. LINQ concepts
Language Integrated Query)Is a set of extensions for c # and Visual Basic languages.It allows writingC # Or Visual Basic code to query memory data in the same way as the database.
The above is the definition from Baidu encyclopedia.
We can see from the English Name Description that,It is a solution that allows developers to retrieve memory data like a database.
2. You need to master the following knowledge points before learning from LINQ:
There are a lot of things, but they are all the basis for learning LINQ well. We have said that, as SQL statements operate on memory data, we must master the basic concepts of tables, fields, and views for learning SQL, the same is true for LINQ.
2.1 implicit type
Before defining variables, We need to specify a type, foreach time, and type. The emergence of implicit types does not need to be done anymore, but we can use var to define it. This is more like a weak type language, such as javascipt. However,. NET is not a weak type language. The implicit type definition is written as follows:
var i=1;var b=”xyz”;var obj=new MyObj();
The above implicit type is equivalent
int i=1;string b=”xyz”;MyObj obj=new MyObj();
Description of implicit types:
A. With the implicit type, you can use var in encoding to define any type of variables.
B. implicit type does not affect program performance ,. NET will help us convert to a specific data type during compilation, so we must declare an implicit type with a value, otherwise. NET does not determine the specific type of conversion and an error is reported.
C. Implicit var saves a lot of time for development. When defining a variable, you need to enter the type twice, and var will do it. During foreach traversal, you can also use var to write the type of the cyclic variable.
2.2 anonymous type
We use the anonymous method instead of declaring the elements and types in the new object. As follows:
// Anonymous var obj = new {str = "abc", Guid. empty, myArray = new int [] {1, 2, 3 }}; Console. writeLine (obj. str); Console. writeLine (obj. empty); Console. writeLine (obj. myArray [0]); Console. readLine ();
The running result is as follows:
After a new object is created, attributes are automatically defined for the object and assigned values to these attributes. When an object's attributes are copied to an anonymous object, you do not need to display the specified attribute name. In this case, the original attribute name will be "copied" to an anonymous object. for example:
The obj. Empty attribute name is automatically created.
If you monitor the variable obj, you will find that the obj Type is Anonymous Type.
Do not try to access the attributes of an object outside the method for creating an anonymous object!
This feature is useful when serializing and deserializing JSON objects in website development.
2.3 automatic attributes
I remember that in the "refactoring" section, we talked about attribute refactoring. We only need to use the "encapsulated field" provided by vs.net on the field name to generate the corresponding attribute for us, such:
(Figure 1)
(Figure 2)
(Figure 3)
Since. net 3.0, the code can be simpler. The Code is as follows:
// Automatic Attribute class Flower {public string Leaf {get; set;} public string Name {get; set ;}}
Refactoring is of course only. net's auxiliary functions will certainly worry about the write efficiency of automatic attributes, which is completely reassuring, just like the var implicit type ,. net will help us complete the compilation, without any performance problems.
2.4 initializer
For initialization of an object, assume there are two objects:
// Initialize the class Flower {public string Leaf {get; set;} public string Name {get; set ;}} class Bear {public Bear (string name) {} public string Name {get; set;} public double Weight {get; set ;}}
In versions earlier than 3.0, we generally write the following code:
// Initialize Flower flower = new Flower (); flower. Leaf = "Leaf"; flower. Name = "cotton ";
In Versions later than 3.0, we can write as follows:
//. Net 3.0 and later object initialization can be written as follows: Flower flower2 = new Flower () {Name = "Peach Blossom", Leaf = "peach Leaf "}; // The constructor carries a parameter object to initialize Bear bear = new Bear ("Polar Bear") {Name = "bear", Weight = 300 }; // set initialization var array = new List <char> () {'A', 'B', 'C', 'D', 'E', 'F '};
We can see that the writing method is much simpler. In particular, the assignment of generic sets is concise and clear.
2.5 anonymous method
Speaking of anonymous methods, that is, when entrusting a method, you can write the method in the delegate statement. Simply put, you do not need to write the method separately. Before talking about this, we would like to introduce the delegation, but in the next section, we will focus on the delegation. Here we only need to understand the anonymous method, the following is an example:
1 // delegate function 2 Func <int, int, string> func1 = Adds; 3 // anonymous method 4 Func <int, int, string> func2 = 5 delegate (int, int B) 6 {7 return a + "+" + B + "equals to what? "+ Environment. newLine + (a + B ). toString (); 8}; 9 // Lambda expression 10 Func <int, int, string> func3 = 11 (a, B) ==>{ return a + "+" + B + "equals to what? "+ Environment. newLine + (a + B ). toString () ;}; 12 13 // call Func delegate 14 string sum = func2 (45, 36); 15 16 Console. writeLine (sum); 17 Console. readLine ();
// Delegate method static string Adds (int a, int B) {return a + "+" + B + "equals to what? "+ Environment. NewLine + (a + B). ToString ();}
By using the anonymous method, you can access the variables in the context. When the method itself is not very long, lightweight writing is very practical.
This is detailed in the delegation in the next section. It doesn't matter if you don't understand it here.
2.6 Extension Method
1) The extension method declaration is defined as a static method in a static class. The first parameter must be identified by the this keyword to indicate the type of extension.
2) The extension method can write the method into the class that didn't provide the method at first. You can also add methods to any class that implements an interface, so that multiple classes can use the same implementation code. (In LINQ, System. Linq. Queryable. cs and System. Linq. Enumerable. cs add extension methods to interfaces)
3) Although the extension method is defined as a static method, you do not need to provide a class name that defines the static method when calling the method. You only need to introduce the corresponding namespace, And the access method is the same as the instance method.
4) The extension method cannot access the private members of the extended type.
Example:
public static IEnumerable<TSource> MyWhere<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { foreach (TSource item in source) { if (predicate(item)) yield return item; }}
Let's take a look at the amazing extension method. To add behavior to a type, you don't have to use the inherited method. You can also write it like this:
var a = "aaa";a.PrintString(); Console.ReadKey();
However, with the above Code, a PrintString method is provided for the string type "extension.
(1) Prerequisites
<1> the extension method must be defined in a non-nested or non-generic static class.
<2> the extension method must be a static method.
<3> the extension method must have at least one parameter.
<4> the first parameter must be prefixed with the this keyword.
<5> the first parameter cannot have other modifiers (such as ref or out)
<6> the first parameter cannot be of the pointer type.
(2) Considerations
<1> like the features mentioned above, the extension method only adds the compiler work and does not affect the performance. (adding a feature for a type by inheritance will affect the performance)
<2> if there is a method in the original class, which is the same as your extension method (at least used), your extension method award will not be called, and the compiler will not prompt you
<3> the extension method is too powerful, which affects the architecture, mode, readability, and so on ....
2.7 iterator
(1) Use
Every time we write a foreach code block for the set type, we use the iterator.
These set types all implement the IEnumerable interface.
Each has a GetEnumerator method.
But this is not the case for array types.
The compiler sets the foreach code block for the array type
Replaced with the for code block.
Let's take a look at the List type signature:
public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
The IEnumerable interface defines only one method:
IEnumerator<T> GetEnumerator();
(2) Advantages of the iterator:
Suppose we need to traverse a huge set.
As long as one element in the Set meets the conditions
The task is completed.
Do you think you need to load all this huge collection into the memory?
Of course not needed (C #3.0 and later )!
Let's take a look at this Code:
Static IEnumerable <int> GetIterator () {Console. writeLine ("iterator returns 1"); yield return 1; Console. writeLine ("iterator returns 2"); yield return 2; Console. writeLine ("iterator returns 3"); yield return 3 ;}
foreach (var i in GetIterator()){ if (i == 2) { break; } Console.WriteLine(i);}Console.ReadKey();
Output result:
The iterator returns 11. The iterator returns 2.
You can see:
When the iterator returns 2, foreach exits.
No output "iterator returns 3"
That is to say, the following work is not done.
(3) yield keywords
The description in MSDN is as follows:
The iterator block is used to provide a value to the enumerated number object or send an iteration end signal.
That is to say, we can determine when to end the iteration logic when generating the iterator.
The above code can be changed to the following format:
Static IEnumerable <int> GetIterator () {Console. writeLine ("iterator returns 1"); yield return 1; Console. writeLine ("iterator returns 2"); yield break; Console. writeLine ("iterator returns 3"); yield return 3 ;}
(4) Considerations
<1> thread security is considered in foreach loop.
During foreach, do not try to remove or add the traversal set.
Any set, even if marked as thread-safe, will cause exceptions when adding or removing items during foreach.
<2> the IEnumerable interface is the core interface of the LINQ feature.
Only the set that implements the IEnumerable Interface
To execute related LINQ operations, such as select and where.
The next section inherits the specific operations of LINQ.
2.8 Lambda expressions
Lambda expressions simply write anonymous methods in a simpler way, which completely simplifies the use of. NET Delegate types.
The Lambda expression in C # is written as "arg-list => expr-body". "=>" indicates the parameter list of the expression on the left, and the expression body on the right ). The parameter list can contain 0 to multiple parameters, separated by commas.
Through the example of the anonymous method above, we can see that the following two pieces of code are equivalent:
// How many times does the anonymous method Func <int, int, string> func2 = delegate (int a, int B) {return a + "+" + B + "equal? "+ Environment. newLine + (a + B ). toString () ;}; // Lambda expression Func <int, int, string> func3 = (a, B) ==>{ return a + "+" + B + "equals to what? "+ Environment. NewLine + (a + B). ToString ();};
Lambda expressions are named after the Lambda (11th Greek letters) algorithm in mathematics, while lambda expressions refer to a simple method for writing anonymity.
3. Key points:
A. LINQ, Language Integrated Query) Is a language extension that allows us to operate on memory data (sets, etc.) Just like querying a database ).
B. Anonymous type:When using new to declare an anonymous type, you do not need to specify the type. NET Versions later than 3.0 can automatically specify the type and attribute name.
C. Automatic attributes:In Versions later than. net 3.0, we define attributes. We only need to simply write get; set;. net will help us to complete the writing in the compilation phase without any performance problems.
D. initializer:In Versions later than 3.0, the initialization of writing objects can be simpler, especially the assignment of generic sets, which is quite concise and clear.
E. Anonymous method:You do not need to specify the method name When entrusting a method. Anonymous methods can be used to access variables in the context. In case of few method code, lightweight delegation is very practical.
F. Extension Method:You can add behavior to a type without using inheritance.
G. iterator:When traversing a large set, you do not need to load it all into the memory, and you only need to meet the conditions to return.
H. Lambda expression:Lambda expressions are named after the Lambda (Greek 11th letters) algorithm in mathematics,Lambda expressions)It refers to a simple method for writing anonymous data..
Note: I have referenced some of my blogs in this article. I would like to express my gratitude for not listing them one by one.
The following section describes how to use LINQ.
========================================================== ========================================================== ====================
Returned directory
<If it is helpful to you, remember to click on the recommendations. If you do not understand the content or do not write it correctly, please contact us more>
========================================================== ========================================================== ====================