From anonymous method to LINQ learning notes

Source: Internet
Author: User
Document directory
  • Anonymous method:
  • Extension Method
  • Lambda expressions
  • Introduction to LINQ

Anonymous method-> Lambda expression-> LINQ, each technology seems to be a source header.

In C # versions earlier than 2.0, the only way to declare a delegate is to use the naming method. C #2.0 introduces anonymous methods. In C #3.0 and later versions, lambda expressions replace anonymous methods as the preferred method for writing Inline code. In one case, the anonymous method provides functions not available in lambda expressions. The anonymous method allows you to omit the parameter list, which means you can convert an anonymous method to a delegate with various signatures. This is impossible for lambda expressions. Adding an extension method to a Lambda expression becomes

Anonymous method:

When no anonymous method is available (C #1.0 ):

 addButton.Click += new EventHandler(AddClick);  void AddClick(object sender, EventArgs e)        {            listBox.Items.Add(textBox.Text);        }
 

With the anonymous method (C #2.0 ):

   addButton.Click += delegate            {                listBox.Items.Add(textBox.Text);            };

The anonymous method allows me to write method code in an "inline" way and associate the Code directly with the delegated instance, making the task of delegation instantiation more intuitive and convenient.

Parameters of the anonymous method

The anonymous method can be followed by a parameter list by the delegate keyword (you can leave it unspecified), and the subsequent code can access these parameters:

 addButton.Click +=  delegate(object sender, EventArgs e)                     {                 MessageBox.Show(((Button)sender).Text);            };

Note the difference between "No parameter list specified" and "parameter list blank"

Addbutton. Click + = delegate {...} // Correct! Addbutton. Click + = delegate (){...} // Error!
Return Value of the anonymous method

If the return value type of the delegate type is void, no value can be returned in the anonymous method;

If the return value type of the delegate type is not void, the returned value of the anonymous method must be compatible with the return value of the delegate type:

  delegate void MyDelegate();            MyDelegate d = delegate{                ……               return;            };
delegate int MyDelegate();MyDelegate d = delegate{……return 100;};
External variables of the anonymous method

Some local variables and parameters may be used by anonymous methods. They are called "external variables of anonymous methods ".

The lifetime of the external variable is extended due to the capture benefit of the anonymous method-until the delegated instance is not referenced.

Static void Foo (double factor) {function f = delegate (int x) {factor + = 0. 2; // factor is the external variable return x * factor;}; invoke (f); // the lifetime of factor is extended}

Unlike local variables, the life cycle of captured variables continues until the delegates that reference the anonymous method meet the garbage collection conditions.

Delegation type inference

C #2.0 allows us to omit the delegate type when instantiating the delegate, and directly use the method name. The C # compiler will make reasonable inferences.

C #1.0 practices:

addButton.Click += new EventHandler(AddClick);Apply(a, new Function(Math.Sin));

C #2.0 practices:

addButton.Click += AddClick;Apply(a, Math.Sin);
Anonymous method Mechanism

In C #2.0, the anonymous method only simplifies the task of delegation instantiation through the additional processing of the compiler. It has no fundamental difference with C #1.0 code.

Through the ildasm.exe Disassembly tool, we can gain an in-depth understanding of the anonymous method:

Anonymous methods in static methods

  public delegate void D();        static void F()        {            D d = delegate { Console.WriteLine("test"); };        }

The above code is converted:

static void F() {D d = new D(__Method1);}static void __Method1() {Console.WriteLine("test");}

Anonymous method in instance method

 class Test        {            int x;            void F()            {                D d = delegate { Console.WriteLine(this.x); };            }        }

The above code is converted:

void F() {D d = new D(__Method1);}void __Method1() {Console.WriteLine(this.x);}

External variables in anonymous methods

 void F()        {            int y = 123;            D d = delegate { Console.WriteLine(y); };        }

The above code is converted:

class __Temp{public int y;public void __Method1() {Console.WriteLine(y);}}void F() {__Temp t = new __Temp();t.y = 123;D d = newD(t.__Method1);}
Extension Method

An extension method can "add" an existing type without creating a new derived type, re-compiling, or modifying the original type in other ways. An extension method is a special static method, but it can be called like an instance method of an extension type. There is no significant difference between calling an extension method and calling a method actually defined in the type.

In the code, you can use the instance method syntax to call the extension method. However, the intermediate language (IL) generated by the compiler converts the code into a call to a static method. Therefore, it does not really violate the encapsulation principle. In fact, extension methods cannot access private variables in their extended types.

public static class Extensions{public static void Foo(this string s) {…..}}String s=“Hello,World”;s.Foo();

The extension method allows us to extend (ADD) the instance methods of the existing type without changing the source code.

Key points of the Extension Method

The essence of an extension method is to change the instance method call to a static method call in the static class during the compilation period.

Note the priority of the extension method: the existing instance method has the highest priority, followed by the static method of the static class under the nearest namespace, and finally the static method of the static class under the distant namespace.

The extension method is a compilation technology. Pay attention to the differences with runtime technologies such as reflection and use them with caution.

Lambda expressions

Use the anonymous method in C #2.0 to search for "All strings containing ABC strings ":

list.FindAll(delegate(string s) {return s.Indexof(“abc”) > 0; });

Use the lambda expression in C #3.0 to find "all strings containing ABC strings ":

list.FindAll(s=>s.Indexof(“abc”) > 0);

The C #2.0 anonymous method allows us to delegate instances in an internal connection mode, the Lambda expression of C #3.0 allows us to use a method that is closer to human thinking and more self-developed to achieve the same effect as the anonymous method.

Lambda expression format:

(Parameter list) => expression or statement Block

There can be multiple parameters, one parameter, or no parameter. Parameter type

It can be implicit or explicit. For example:

(X, y) => X * y // multiple parameters, implicit type => Expression

X => X * 10 // single parameter, implicit type => Expression

X =>{ return x * 10;} // single parameter, implicit type => statement Block

(Int x) => X * 10 // single parameter, explicit type => Expression

(Int x) =>{ return x * 10;} // single parameter, explicit type => statement Block

() => Console. writeline () // No Parameters

Key Points of Lambda expression format

• The parameter types of lambda expressions can be ignored because they can be inferred based on the context.

• The body of a Lambda expression can be an expression or a statement block.

• The arguments passed in by lambda expressions are involved in type inference and method overload analysis.

• Lambda expressions and expressions can be converted into expression trees.

Lambda expressions and delegate types

Lambda expression l can be converted to delegate type D, which must meet the following conditions:

• L and D have the same number of parameters.

• The parameter type of l must be the same as that of D. Note that implicit types must be involved in type discrimination.

• D returns the same type as l, whether expression or block.

Introduction to LINQ

Oo (Object Oriented): access and integration of information. Relational databases and XML are typical applications.

•. Net Language Integrated Query (LINQ): uses a general solution to address access and integration of various information sources instead of proprietary solutions specific to relational databases or XML.

• In LINQ, query is an integral part of the programming language, which enables the query expression to get good syntax checks during compilation, rich metadata, and advantages of smart sensing among other strong languages.

LINQ expressions
 class app    {        static void Main()        {            string[] names = { "Burke", "Connor", "Frank","Everett", "Albert", "George","Harris", "David" };            IEnumerable<string> query = from s in names                                        where s.Length == 5                                        orderby s                                        select s.ToUpper();            foreach (string item in query)                Console.WriteLine(item);        }    }
Query expression Parsing
IEnumerable<string> query = from s in nameswhere s.Length == 5orderby sselect s.ToUpper();

The semantics is equivalent to the following "method-based Query ":

IEnumerable<string> query = names.Where(s => s.Length == 5).OrderBy(s => s).Select(s => s.ToUpper());

Note that the parameter is a Lambda expression, similar to the following delegate:

Func<string, bool> filter = delegate (string s) {return s.Length == 5;};Func<string, string> extract = delegate (string s) {return s; };Func<string, string> project = delegate (string s) {return s.ToUpper(); };IEnumerable<string> query = names.Where(filter).OrderBy(extract).Select(project);

Query operators are another important facility in LINQ. LINQ uses extension methods to define query operators, such as the where OPERATOR:

namespace System.Linq{    public static class Enumerable    {        public static IEnumerable<T> Where<T>(        this IEnumerable<T> source, Func<T, bool> predicate)        {            foreach (T item in source)                if (predicate(item))                    yield return item;        }    }}

To call the extension method in a common way:

IEnumerable<string> query = Enumerable.Where(names,s => s.Length < 6);

C # language allows us to use the following method to call the extension method:

IEnumerable<string> query = names.Where(s => s.Length < 6);
 

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.