Language Integrated Query. Many people are familiar with the SQL language and it is very convenient to use it to operate the database. Now, in C #3.0, you can use the same syntax to operate various types of data, including arrays, files, and databases. As there are many things in LINQ, I want to talk about it three times. For the first time, I will mainly talk about LINQ. For the second time, I will mainly talk about using LINQ to operate databases. For the third time, I will introduce how to use LINQ to operate XML, the fourth section mainly introduces some function applications of LINQ. I have time to write some special topics about LINQ.
The following is an example in which a programmer should talk with the code:
Class Program
...{
Static void Main (string [] args)
...{
String [] names =... {"Everett", "Albert", "George", "Harris", "David "};
Var items = from name in names
Where name. Length> = 6
Orderby name
Select name. ToUpper ();
Foreach (var item in items)
Console. WriteLine (item );
}
}
Are you familiar with the from, where, orderby and other words above? We can easily query some arrays like a database. In fact, the above expression is equivalent to the following statement:
Var items = names. Where (name => name. Length> = 6). OrderBy (name => name). Select (name => name. ToUpper ());
So why can we apply these methods on arrays? These methods are not available on arrays? Let's recall what we said, the extension method, right. here we can see the application of the extension method. We can also see that the application of Lambda expressions makes the statements more concise and easy to understand. Where are these extension methods defined? We can see this definition in the System. LINQ assembly:
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;
}
}
}
Here we can clearly see many this keywords, which are the symbols of the extension method. If we are not very familiar with Lambda expressions, the above LINQ statements can be further converted into the form of delegation.
Func <string, bool> filter = delegate (string s)... {return s. Length> = 6 ;};
Func <string, string> extract = delegate (string s)... {return s ;};
Func <string, string> project = delegate (string s)... {return s. ToUpper ();};
Var items = names. Where (filter). OrderBy (extract). Select (project );
There is a problem. We will notice that var is used as its type before items. Is there any question about the type of var? Let's take a closer look at the System. LINQ assembly and we will find that the expansion method returns the IEnumerable <T> type, a generic interface. That's right, var is the generic interface. Another problem is that when names meets certain conditions, we can use the LINQ expression for query. This should be carefully observed from that Assembly. We will find that there is a source parameter. According to the syntax of the extension method, we know that this source parameter is the object that calls this method. We can infer that this object must be converted to IEnumerable <T>. So what type can be converted successfully? Obviously, only the type of the generic interface IEnumerable <T> can be converted. For example, the array type, List <T>, and so on. When we can also define the type, as long as this interface is implemented, we can operate on this type with LINQ.
This is just a brief introduction to LINQ. In the future, we will talk about some specific applications. However, from the introduction, we can see some powerful functions of LINQ.
Linq to SQL is a database application of LINQ technology. Database technology from OLEDB, odbc to ado, to ado. net to the present of the linq to SQL, making it easier for programmers TO operate databases. The purpose of LINQ is to make queries no longer exist. Of course, queries to databases should be included. Not only can the database be queried, but also CUID (Create, Update, Insert, Delete) can be implemented and very convenient.
The following describes query and addition, deletion, and modification.
To query the data in a database table, you must first establish a ing to the database table. Just like to use ADO. NET, you need to first store the data in the database to DataSet and take a look at the code.
/* Note that the [Table] feature corresponds to the Table named "Category" in the database. The [Column] feature corresponds to the columns in the database. */
// I don't want to explain it in detail here. I will introduce these topics in the future when I write my own special topics.
[Table (name = "category")]
Public class category
...{
[Column (isprimarykey = true)]
Public String categoryid;
[Column]
Public string name;
[Column]
Public String descn;
}
The above is a ing of the data table. The database used is the database northwind that comes with SQL Server2000. In fact, people who have written C # should be able to understand the above Code. After the table ing is established, you can perform corresponding operations on the table.
Note that we use manual data table ing here. In fact, Ms provides us with the corresponding automatic tool sqlmetal. You can use this tool to automatically generate code for database table ing, which is highly efficient, you can change the generated code if you have any changes.
The following query is available:
Datacontext DB = new datacontext ("Server = localhost; database = northwind; trust_connection = true ");
// Modify the connection string based on your configuration.
Table <Category> categorys = dB. gettable <Category> ();
VaR result =
From C in categorys
Select C;
// You Can See That DataContext is equivalent to Connection in ADO. NET, but it provides more powerful functions.
// The result is equivalent to IEnumerable <Category>. If you do not know why this is introduced, refer to the Lambda expression I wrote.
// The content in the result can be output below
Foreach (var c in result)
Console. WriteLine ("CategoryId = {0}, Name = {1}, Descn = {2}", c. CategoryId, c. Name, c. Descn );
/** // * The following describes the intelligent perception of LINQ. If you are using a LINQ project created by the VS2005 + LINQ plug-in, there is no smart awareness of linq to SQL in. That is to say, when you write c in the output, there will be no content, but you can write the corresponding fields according to the self-built ing, and there is no problem in compiling and running. If you use VS2008, that is, the LINQ project code "Orcas", then intelligent sensing is supported. Very important */
The above is the query of the database. we can write a very complex query. In fact, internally, LINQ will convert your written LINQ statements into SQL statements and send them to the database for execution. Then return the corresponding result. If you want to see the converted SQL statement, you can add db. Log = Console. Out after the connection is established. In this way, the program will automatically output SQL statements and query results. Here is a brief introduction to how to query. We know that there is a relationship between the table and the table. We will explain these complicated things in detail later.
Next let's take a look at how to change it.
// Change
String id = "DOGS ";
Var cat = db. Categories. Single (c => c. CategoryId = id );
Cat. Name = "New Dogs ";
// Add
Product P = new product ...{.......};
Cat. Products. Add (P );
// Delete
String id = "dogs ";
VaR cat = dB. categories. Single (C => C. categoryid = ID );
DB. categories. Remove (CAT)
// Submit changes
DB. submitchanges ();
// Note that submichanges () has changed the Object layer to the data layer. That is to say, if you do not submit the changes, the changes will not be stored in the database.
The above is just a brief introduction to LINQ to SQL. In fact, there are still a lot of content in it. This topic will be described in detail later when writing a special article on LINQ.
If you want to learn more about LINQ to SQL, you can download the video at the following address. Click to enter>
We know that W3C has a DOM model and C # has a class library that operates XML under the DOM model. However, after the emergence of LINQ, Microsoft re-built a set of XML models, and the operations were the same as those of the DOM model, but they were simpler.
The following figure shows the model:
The above is a new class library. The core class is the xelement. It is definitely the core class, but it should not be regarded as a low level. Some other features are different from the DOM model. One of them is that xattribute and xnode are at the same level, and xdocument is no longer necessary. For other differences, see the DOM model for comparison.
The following code compares the differences between the DOM model and the LINQ model in operating XML:
// Dom Model
Xmldocument Doc = new xmldocument ();
Xmlelement name = Doc. createelement ("name ");
Name. innertext = "Patrick Hines ";
Xmlelement phone1 = Doc. createelement ("phone ");
Phone1.setattribute ("type", "home ");
Phone1.innertext = "206-555-0144 ";
Xmlelement phone2 = Doc. createelement ("phone ");
Phone2.setattribute ("type", "work ");
Phone2.innertext = "425-555-0145 ";
Xmlelement street1 = Doc. createelement ("street1 ");
Street1.innertext = "123 Main St ";
Xmlelement city = Doc. createelement ("city ");
City. innertext = "Mercer Island ";
Xmlelement state = Doc. createelement ("state ");
State. innertext = "wa ";
Xmlelement postal = Doc. createelement ("Postal ");
Postal. InnerText = "68042 ";
XmlElement address = doc. CreateElement ("address ");
Address. AppendChild (street1 );
Address. AppendChild (city );
Address. AppendChild (state );
Address. AppendChild (postal );
XmlElement contact = doc. CreateElement ("contact ");
Contact. AppendChild (name );
Contact. AppendChild (phone1 );
Contact. AppendChild (phone2 );
Contact. AppendChild (address );
XmlElement contacts = doc. CreateElement ("contacts ");
Contacts. AppendChild (contact );
Doc. AppendChild (contacts );
// LINQ Model
XElement contacts =
New XElement ("contacts ",
New XElement ("contact ",
New xelement ("name", "Patrick Hines "),
New xelement ("phone", "206-555-0144 ",
New xattribute ("type", "home ")),
New xelement ("phone", "425-555-0145 ",
New xattribute ("type", "work ")),
New xelement ("Address ",
New xelement ("street1", "123 Main St "),
New xelement ("city", "Mercer Island "),
New xelement ("State", "wa "),
New xelement ("Postal", "68042 ")
)
)
);
From the comparison, we can also see the simplicity of the LINQ model. We can also see the importance of xelement from the LINQ model. You can use xelement to not only create XML files from the beginning, but also load the files. You can also retrieve the required elements from the database, which requires the use of the content of the LINQ to SQL statement. You can also retrieve the elements from the array. After the operation is complete, you can save it using the Save method.
The following describes how to add, delete, query, and modify XML.
// Query
Foreach (C in contacts. nodes ())...{
Console. writeline (C );
}
We can see that each element does not need to be forcibly converted when outputting XML elements. Here, the C # compiler has done these tasks, it calls the ToString () method of each element during output.
// Insert element
XElement mobilePhone = new XElement ("phone", "206-555-0168 ");
Contact. Add (mobilePhone );
Here is just a simple demonstration of some operations. For those complex operations, as long as the DOM model can implement the LINQ model, it will be able to implement. You can also use AddAfterThis and AddBeforeThis to improve efficiency during insertion.
// Delete an element
Contact. Element ("phone"). Remove (); // delete a specific Element
Contact. Elements ("phone"). Remove (); // delete a group of elements
Contacts. element ("Contact"). element ("Address"). removecontent (); // Delete the content of an element
The setelement method can also be used to delete an element. Setting an element to null deletes the element.
// Modify the element
Contact. element ("phone"). replacecontent ("425-555-0155"); // modify the content of the first phone element.
Of course, you can also use the setelement method. This is where it is used.
From the above brief introduction, we can clearly see how simple it is to operate XML using LINQ. Here, the C # syntax is used. If VB. NET is used, it will be simpler. Some methods can be used in VB. NET, but not in C. After all, VB. NET is a late binding language and can give full play to its advantages.
This time, let's take a look at some function operations provided by LINQ. Let's take a look at the function list below:
List of standard LINQ query operators Operator
Lazy?
Description
Aggregate
No
Applies a function to a sequence, yielding a single value.
All
No
Applies a function to a sequence to see if all elements satisfy the function.
Any
No
Applies a function to a sequence to see if any element satisfies the function.
Average
No
Computes the average of a numeric sequence.
Cast
Yes
Yields the elements of a sequence type-casted to a given type.
Concat
Yes
Yields the concatenation of two sequences S1 and S2.
Contains
No
Searches a sequence to see if it contains a given element.
Count
No
Counts the number of elements in a sequence, yielding an integer result.
DefaultIfEmpty
Yes
Given a sequence S, yields S or a sequence with the default value if S is empty.
Distinct
Yes
Returns a sequence with duplicates eliminated.
ElementAt
No
Returns the ith element of a sequence.
ElementAtOrDefault
No
Returns the ith element of a sequence, or the default value if sequence is empty.
Empty
Yes
Yields an empty sequence.
Revoke all
No
Compares two sequences for equality.
Except
Yes
Given two sequences S1 and S2, returns the set difference S1 S2.
First
No
Returns the first element of a sequence.
FirstOrDefault
No
Returns the first element of a sequence, or the default value if sequence is empty.
Fold
No
Obsolete, see Aggregate.
GroupBy
Yes
Groups the elements of a sequence by key.
GroupJoin
Yes
Performs a join of two sequences S1 and S2, yielding a hierarchical result.
Intersect
Yes
Given two sequences S1 and S2, returns the set intersection of S1 and S2.
Join
Yes
Performs a traditional inner equijoin of two sequences S1 and S2.
Last
No
Returns the last element of a sequence.
LastOrDefault
No
Returns the last element of a sequence, or the default value if sequence is empty.
LongCount
No
Counts the number of elements in a sequence, yielding a long result.
Max
No
Returns the maximum of a sequence.
Min
No
Returns the minimum of a sequence.
OfType
Yes
Yields the elements of a sequence that match a given type.
OrderBy
Yes
Orders a sequence of elements by key into ascending order.
OrderByDescending
Yes
Orders a sequence of elements by key into descending order.
Range
Yes
Yields a sequence of integers in a given range.
Repeat
Yes
Yields a sequence of values by repeating a given value n times.
Reverse
Yes
Reverses the elements of a sequence.
Select
Yes
Applies a projection function to a sequence, yielding a new sequence.
Selectworkflow
Yes
Applies a projection function to flatten a sequence of sequences.
Single
No
Returns the lone element of a singleton sequence.
Singleordefault
No
Returns the lone element of a singleton sequence, or default if sequence is empty.
Skip
Yes
Skips the first n elements of a sequence, yielding the remaining elements.
Skipwhile
Yes
Given function f and sequence S, skips the initial elements of s where F is true.
Sum
No
Computes the sum of a numeric sequence.
Take
Yes
Yields the first n elements of a sequence.
Takewhile
Yes
Given function f and sequence S, yields the initial elements of s where F is true.
Thenby
Yes
Takes an ordered sequence and yields a secondary, ascending ordering.
TheyByDescending
Yes
Takes an ordered sequence and yields a secondary, descending ordering.
ToArray
No
Iterates requests ss a sequence, capturing results in an array.
ToDictionary
No
Iterates triggers ss a sequence, capturing results in a Dictionary <K, V>.
ToList
No
Iterates requests ss a sequence, capturing results in a List <T>.
ToLookup
No
Iterates requests ss a sequence, capturing results in a Lookup <K, IEnumerable <V>.
ToSequence
Yes
Casts a sequence as an IEnumerable sequence for use with standard query ops.
Union
Yes
Given two sequences S1 and S2, returns the set union of S1 and S2.
Where
Yes
Applies a Boolean function to a sequence, yielding a sub-sequence.
Which of the following describes LAZY in the second column? . We know the term Lazy Evalution. That is to say, the program does not evaluate it when it is not in use.
The following is an example:
Class Doctor
...{
Public string Name;
Public int Initials;
}
Public static bool dump (Doctor d)
...{
System. Console. WriteLine (d. Initials );
Return true;
}
Doctor [] doctors =... {new Doctor... {Name = "Mary", Initials = 123 },
New Doctor... {Name = "Jack", Initials = 456 },
New Doctor... {Name = "Maggie", Initials = 789}
};
Var query = from d in doctors
Where dump (d)
Select d;
What will the above Code output ?? The answer is Nothing. Because the query statement is not executed at all. That is to say, the query statement is actually executed only when the query variable is used below. You can add this sentence after writing the query statement.
Foreach (var q in query );
This will output the content. This is a simple explanation of Lazy Evalution. This method has many advantages. I will not discuss it here. We can also see that not all LINQ functions have applied Lazy Evalution. Try it by yourself.
The following describes several important topics:
1 Any (the following example uses the Doctor written above)
// Check whether there is a doctor named Lary. If yes, true is returned. If no, false is returned.
Bool inLakeForest = doctors. Any (doc => doc. Name = "Lary ");
// Equivalent
Var query = from doc in doctors
Where doc. Name = "Lary"
Select doc;
Bool inLakeForest = query. Any ();
2 Cast
System. Collections. ArrayList al = new System. Collections. ArrayList ();
Al. Add ("abc ");
Al. Add ("def ");
Al. Add ("ghi ");
Var strings = al. Cast <string> ();
Foreach (string s in strings) // "abc", "def", "ghi"
Console. WriteLine (s );
// Cast is mainly used to enable LINQ to be applied to non-generic sets.
3 Distinct
Int [] ints =... {1, 2, 2, 3, 2, 3, 4 };
Var distinctInts = ints. Distinct ();
Foreach (var x in distinctInts) // 1, 2, 3, 4
Console. WriteLine (x );
// Mainly returns different elements in a collection.
4 TB
Int [] intss1 =... {1, 2, 2, 3, 2, 3, 4, 5, 6 };
Int [] intss2 =... {1, 3, 6, 7 };
VaR diffints = intss1.20.t (intss2 );
Foreach (var x in diffints) // 2, 4, 5
Console. writeline (X );
// You can query the elements that appear in one set but cannot appear in another set.
5 first
Int [] ints =... {1, 2, 3, 4, 5, 6 };
Int first = ints. First ();
Doctor = doctors. First (Doc => Doc. Name = "Mary ");
Console. writeline (first); // 1
Console. writeline (doctor. initials); // 123
// Returns the first element that meets the condition in the set.
6 orderby
Int [] ints =... {3, 1, 6, 4, 2, 5 };
VaR sorted = ints. orderby (x => X );
Foreach (var x in sorted) // 1, 2, 3, 4, 5, 6
Console. writeline (X );
// Sorting. You can also use orderbydescending and reverse sorting.
7 select
Int [] ints =... {1, 2, 3, 4, 5, 6 };
VaR sameints = ints. Select (x => x> = 3 );
Foreach (var x in sameints) // 3, 4, 5, 6
Console. writeline (X );
// Select the elements that meet the conditions
8 sum
Int [] ints =... {1, 2, 3, 4, 5, 6 };
Decimal? [] Values =... {1, null, 2, null, 3, 4 };
Int sum1 = ints. sum ();
Decimal? Sum2 = values. Sum ();
Console. WriteLine (sum1); // 21
Console. WriteLine (sum2); // 10
// Sum, which can be applied to int, int ?, Long, long ?, Decimal, decimal ?, Double, or double ?. For these types, the return value is the same as the preceding type.
9 ToList
Doctors doctors = new Doctors ();
Var query = from doc in doctors
Where doc. Name = "Mary"
Select doc;
List <Doctor> chicago = query. ToList ();
// Convert the query result to a List set
10 Where
Int [] ints =... {1, 2, 3, 4, 5, 6 };
Var even = ints. Where (x => x % 2 = 0 );
Foreach (var x in even) // 2, 4, 6
Console. WriteLine (x );
// Returns a set of elements that meet the conditions.
I would like to introduce these items first, and others will explore them on their own.