What is a chain in C #?

Could you tell me what this construction is in C #.

Code Golf: the numerical equivalent of an Excel column name

C.WriteLine(C.ReadLine() .Reverse() .Select((c, i) => (c - 64) * System.Math.Pow(26, i)) .Sum()); 

Although I am new to C # (just two months so far), but since I joined the C # team, I have never seen such chains. It really attracted me , and I want to know more about it.

Please give some idea about this.

+6
c #
source share
4 answers

Such a chain of methods is often called a free interface .

You can create your own free interface by implementing functions that return the object on which they were called.

For a trivial example:

 class Foo { private int bar; public Foo AddBar(int b) { bar += b; return this; } } 

What can be used as:

 Foo f = new Foo().AddBar(1).AddBar(2); 

You can also implement a free interface using extension methods.

For example:

 class Foo { public int Bar { get; set; } } static class FooExtensions { public static Foo AddBar(this Foo foo, int b) { foo.Bar += b; return foo; } } 

and etc.

Here is a more complex example. Finally, Autofac and CuttingEdge.Conditons are two examples of open source libraries that have a very nice interface.

+9
source share

There is nothing special about most of the expression, but the select method uses lambda expressions , the key component of Language Integrated Query is LINQ for short.

A .NET-integrated query defines a set of general-purpose standards query operators that allow crawl, filter, and projection to be expressed in a direct declarative way on any .NET-based programming language.

LINQ and its lambda expressions are a way to write complex query expressions and manipulations concisely and readily. It was added to the .NET Framework in 3.5. Here is more information from MSDN .

+2
source share

This is a little more than a chain of function calls with some indentation, where C calls ReadLine (), the result of which is used for Reverse, the result of which is used for Select, etc. the functions themselves are part of LINQ, those that are after using syntactic sugar. Here is a list of LINQ query functions along with samples when using them, and here is a tutorial for LINQ.

(In case you are interested in: Reverse () returns IEnumerable, which goes from the back to the front of the given IEnumerable, Select () returns IEnumerable, listing all the elements, after applying this expression, lambda and Sum () simply returns the sum of all the elements of this IEnumerable. )

+2
source share

The chain template can be called a free interface. This happens when an interface function (or extension method) returns the same interface. In this case, it is IEnumerable.

You also have LINQ added there with Select and Sum functions

+1
source share

All Articles