1.4.1.1 use LINQ to process data
If you are using LINQ, this example is just a reminder, but we will use it to show more important content. The sample code here processes data using a standard imperative programming style.
Listing 1.3 imperative Data Processing (C #)
Ienumerable <string> getexpenisveproducts (){
List <string> filteredinfos = newlist <string> (); [1]
Foreach (product inproducts) {[2]
If (product. unitprice> 75.0 m ){
Filteredinfos. Add (string. Format ("{0}-$ {1 }",
Product. productname, product. unitprice); [3]
}
}
Return filteredinfos;
}
As you can see, the Code is the basic command sequence, which is imperative. The first statement creates a new list [1] and the second statement traverses all products [2]. The following statement adds the elements to the list [3]. However, we want to be able to describe the problem at a higher level and use a more abstract term, that is, this code filters a set and returns information about all qualified products.
In C #3.0, we can use a query expression to write the same code. The version in listing 1.4 is closer to our real goal and uses the same idea to filter and convert data.
Listing 1.4 declarative Data Processing (C #)
Ienumerable <string> getexpenisveproducts (){
Return from product inproducts
Where product. unitprice> 75.0 M [1]
Selectstring. Format ("{0}-$ {1 }",
Product. productname, product. unitprice); [2]
}
The calculation result (filteredinfos [may be a written mistake. This variable is not found in the Code. It should be the filtered information.]) Is composed of basic operators, such as select or where. These operators use other expressions as parameters because they need to know the filtering and selection as the result. Compared with the previous Code, these operators use new methods to combine code, which also expresses our intent, but write less code. Note that in listing 1.4, the entire expression that computes a description result is not a sequence of statements. You will see this trend repeatedly throughout the book. In a more declarative language, such as F #, everything written is an expression.
Another thing that makes sense in this list is that many technical details of the solution are transferred to basic operators. In this way, the code is simpler and more flexible, because we only need to change the implementation of the operator, instead of making major changes to the code using the operator. Later, we will see that this method makes it easier to process data in parallel.
LINQ is not the only mainstream. NET technology that relies on Declarative Programming. Next, we will focus on the Windows Presentation Layer BASICS (Windows Presentation Foundation, WPF) and The XAML language.