Linq to XML component-you can select and operate XML files by mistake, which is more convenient than XML operations by Xpath.Ii. What are the benefits of using Linq?
In the first part, it is mentioned that Linq includes four components, which are operations for adding, deleting, modifying, and querying different data. However, in the past, related technologies were also used to operate the data (for example, for database operations, there were previously Ado.. Net. XML operations can also be performed using XPath to operate XML files ), at this point, everyone should have a question: why do we still need to use the relevant technologies to support it? The answer to this question is very simple. Linq makes it easier to operate these data sources, which is easy to understand. The previous technical operations are too complicated, so Microsoft is motivated, I hope this can be done better. Therefore, we have proposed in C #3 to help you operate these data sources. The following comparison shows how easy and convenient Linq is:
2.1 query data in a set
Previously, we used the for or foreach statement to query data in the Set, while the query expression is used for the query by the Linq expression, which is more concise than the previous for or forach method, it is easier to add filtering conditions. Let's take a look at the comparison code of the two methods (let's assume a scenario -- return an element with an even number in the set)
The following code uses the foreach statement to return elements with an even number:
Static void Main (string [] args) {# region Linq to objects comparison Console. writeLine (query the collection object using the old method, and the query result is :); OldQuery (); Console. writeLine (use the Linq method to query collection objects. The query result is:; LinqQuery (); Console. read (); # endregion} # region Linq to Objects comparison // comparison of using Linq and using Foreach statements // 1. use foreach to return the private static void OldQuery () {// initialize the queried data List
Collection = new List
(); For (int I = 0; I <10; I ++) {collection. add (A + I. toString ();} // creates a List of saved query results.
QueryResults = new List
(); Foreach (string s in collection) {// gets the element serial number int index = int. parse (s. substring (1); // if (index % 2 = 0) {queryResults. add (s) ;}/// output the query result foreach (string s in queryResults) {Console. writeLine (s) ;}// 2. use Linq to return the private static void LinqQuery () {// initialize the queried data List
Collection = new List
(); For (int I = 0; I <10; I ++) {collection. add (A + I. toString ();} // create a query expression to obtain the element var queryResults = from s in collection let index = int. parse (s. substring (1) where index % 2 = 0 select s; // output the query result foreach (string s in queryResults) {Console. writeLine (s) ;}# endregion
From the comparison of the two methods above, we can see that the use of Linq to query a set is much simpler, and it is also easy to add filtering conditions (you only need to add additional filtering conditions after Where ), of course, the running results are also our expectation. The running results are also attached below:
2.2 query XML files
In the past, most of us used XPath to query XML files. However, to query XML files using XPath, we need to first know the specific structure of the XML file. While the Linq query expression is used to query XML data, you do not need to know the XML file structure, and the encoding is simpler, so it is easy to add judgment conditions, the following code illustrates the benefits of using a Linq query (assume a scenario -- an XML file that defines Persons, now we need to find the element with the Name node "Li Si" in the XML file ):
Static void Main (string [] args) {# region Linq to XML comparison Console. writeLine (use XPath to query XML files. The query result is:; OldLinqToXMLQuery (); Console. writeLine (use the Linq method to query XML files. The query result is:; UsingLinqLinqtoXMLQuery (); Console. readKey (); # endregion} # region Linq to XML comparison // initialize XML data private static string xmlString =
+
+
Zhang San
+ 18+
+
+
Li Si
+ 19+
+
+
Wang Wu
+ 22+
+
; // Use XPath to query XML files private static void OldLinqToXMLQuery () {// import XML file XmlDocument xmlDoc = new XmlDocument (); xmlDoc. loadXml (xmlString); // create an XPath string xPath =/Persons/Person to query the XML file; // query the Person element XmlNodeList querynodes = xmlDoc. selectNodes (xPath); foreach (XmlNode node in querynodes) {// query the element foreach (XmlNode childnode in node) whose name is Li Si. childNodes) {if (childnode. innerXml = Li Si) {Console. writeLine (Name: + childnode. innerXml + Id: + node. attributes [Id]. value) ;}}}// use Linq to query the XML file private static void UsingLinqLinqtoXMLQuery () {// import XML XElement xmlDoc = XElement. parse (xmlString); // create a query and obtain the element var queryResults = from element in xmlDoc. elements (Person) where element. element (Name ). value = Li Si select element; // output the query result foreach (var xele in queryResults) {Console. writeLine (Name: + xele. element (Name ). value + Id: + xele. attribute (Id ). value) ;}# endregion
When you use XPath to query XML files, you first need to know the specific structure of the XML file (in the code, you need to specify XPath as/Persons/Person, this means that you must know the composition structure of XML.) However, you do not need to know the XML document structure in the use of Linq. You can also see the conciseness of the use of Linq in terms of the amount of code writing, the running result is attached below:
I will not give the examples of the following:
- The usage of the Linq query expression is simpler and easier to understand (people who have never been familiar with Linq can roughly guess what the Code intends to be)
- With more functions provided by Linq, We can query, sort, group, add and delete most of the operation data.
- You can use Linq to process a variety of data sources, or define your own Linq implementation for a specific data source (this will be an introduction to the in-depth understanding of Linq)
Iii. Examples of the actual operations of Linq-use Linq to traverse file directories
Through the previous two sections, you can get to know the strength of Linq. In this section, we will give an example to see what can be done with Linq? If you want to build a file management system, you need to traverse the file directory. Next we will use Linq to find out whether a specific file exists in the file directory. The specific code is as follows:
Static void Main (string [] args) {string desktop = Environment. GetFolderPath (Environment. SpecialFolder. Desktop); // FileQuery2 (desktop); if (! String. isNullOrEmpty (FileQuery () {Console. writeLine (FileQuery ();} else {lele.writeline(text.txt file does not exist on the computer desk);} Console. read ();} // use Linq to query the table. // query whether the text.txt file is private static string FileQuery () {string reply topdir = Environment. getFolderPath (Environment. specialFolder. desktop); // obtain the file name string [] filenames = Directory in the specified Directory and subdirectory. getFiles (shorttopdir ,*. *, SearchOption. allDirectories); List
Files = new List
(); Foreach (var filename in filenames) {files. add (new FileInfo (filename);} var results = from file in files where file. name = text.txt select file; // output the query result StringBuilder queryResult = new StringBuilder (); foreach (var result in results) {queryResult. appendLine (file path: + result. fullName);} return queryResult. toString ();}///
/// Use recursion to find the file. // query the table store's text.txt file ///Private static void FileQuery2 (string path) {// obtain the files (including subdirectories) in the specified Directory string [] filenames = Directory. GetFiles (path); List
Files = new List
(); Foreach (var filename in filenames) {files. add (new FileInfo (filename);} var results = from file in files where file. name = text.txt select file; // output the query result StringBuilder queryResult = new StringBuilder (); foreach (var result in results) {Console. writeLine (file path: + result. fullName);} // obtain all subdirectories string [] dirs = Directory. getDirectories (path); if (dirs. length> 0) {foreach (string dir in dirs) {FileQuery2 (dir );}}}
The running result is:
My desktop file is:
Desttop folder text.txt mytext folder text folder text.txt
Iv. Summary
The content of this topic has been introduced here. This topic will briefly share with you my understanding of Linq and hope to give you a rough idea of Linq, in the subsequent in-depth understanding of the Linq series, we will discuss with you the implementation principles of the Linq. This topic is also the last feature in C #3. The next topic will introduce one of the most important features in C #4-dynamic type (dynamic ).