C# study notes Linq

Basic usage of Linq

Linq, language intergrated query is a set of extensions for C#. Using Linq, you can query memory data such as collections, as well as query database (datebase) and XML (standard universal markup language) data, which are respectively called Linq to object, Linq to datebase and Linq to XML. Here is Linq to object.
Linq's writing method is similar to the query syntax of database SQL statements.

	from 变量名 in 集合 where 条件 select 结果变量

Among them, the variable name is a temporary variable, the collection is an array or other collection objects, the condition is generally a logical expression for the variable, and the result variable is generally an expression for the variable name (it can be the variable itself). E.g:

	from n in arr where n > 5 select n;

Means arrto find elements greater than 5 from the array ( n), and finally select these n.
If the square of these numbers is selected, it is:

	from n in arr where n > 5 select n * n;

For the numbers that meet the conditions, you can sort them in descending order first, and then output the results, such as:

	from n in arr where n > 5 orderby n descending select n * n;

Example 1

Query intthe numbers greater than in the array and arrange them in order of size:

	static void Main(string[] args) {
    
    
		Random rnd = new Random();
		// 示例1,查询int数组中大于10的数字,并按照大小顺序排列:
		int[] arr = new int[20];
		for (int i = 0; i < arr.Length; i++) arr[i] = rnd.Next(20);
		var m = from n in arr where n > 10 orderby n descending select n;
		foreach (var n in m)
			Console.Write(n + " ");
		Console.WriteLine();
	}

operation result:
Insert picture description here

As you can see from the above example, the Linqquery syntax is very similar to the SQL query syntax, but it should be fromput in front, so that the type of the variable can be inferred, and it is convenient for the integrated development environment to perform intellisence.
LinqThe result of the query returns an enumerator object, which implements the IEnumerableinterface. The type of this object is generally very complex. It varis represented by a type, and the compiler automatically infers its type. This varobject can be used foreachto traverse. LinqThe result of some queries is a "queryable object" that implements an IQuerableinterface. Since the IQuerableinterface is IEnumerablea sub-interface of the interface, more complex operations can be performed on it.
Worthy of note are: the enumerator varobject and does not really begin query, use only when foreachthe time to traverse, query process really perform.

Example 2

A slightly more complicated Linq query, using the group grouping function:

	static void Main(string[] args) {
    
    
		// 示例2,一个稍微复杂的Linq查询,使用group分组功能:
		string[] languages = {
    
     "Java", "C#", "C++", "Delphi", "VB.net", "VC.net", "Perl", "Python" };
		var query = from item in languages
					group item by item.Length into lengthGroups
					orderby lengthGroups.Key
					select lengthGroups;
		foreach (var group in query) {
    
    
			Console.WriteLine("strings of length{0}", group.Key);
			foreach (var str in group) {
    
    
				Console.WriteLine(str);
			}
		}
	}

Operation result:
Insert picture description here
In this example, lengththe data is grouped according to the character length ( ) ( group) and put into the lengthGroupsvariable, and sorted by the grouping keyword ( .Key). The resulting enumerator is foreachtraversed in a double loop.

Linq's query method

About 40 defines Linq query operators, such as select, from, in, whereand orderbythe like.

1. Two ways to write Linq

One form is query expression syntax, and the other is a query method that is closer to SQL syntax and is more readable.
Another form is query method syntax (method syntax), which mainly uses System.Linq.Enumerablethe extension method defined in the class and the Lambda expression method for query. E.g:

	List<int> arr = new List<int>() {
    
     1, 2, 3, 4, 5, 6, 7 };
	var result = arr.Where(a => a > 3).Sum();
	Console.WriteLine(result);

In this code, two extension methods are used.
One is the Whereextension method, which needs to pass in a Func<int, bool>type of generic delegate, which means to intjudge an element ( variable of the type) ( a > 3), and the return value is the booltype. Here is the direct a => a > 3transfer this Lambda expressions to the Wheremethod.
The other is the Sumextension method, which calculates the sum of Wherethe collection returned by the extension method.
Using the whereequal clause actually calls the Enumerableextension method defined in the class.

2. Extension method

The so-called "extension methods" here are staticglobal functions defined in the class. It can take thisparameters, which means that a method is applied to a certain object, and the compiler will automatically convert it to an extension method. transfer.

Example

Extension methods to String:

using System;
public static class ExtensionMethodString
{
    
    
	public static int WordCount(this string s) {
    
    
		string[] words = s.Split(" ,;.!".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
		return words.Length;
	}
}
class Demo
{
    
    
	static void Main(string[] args){
    
    
		string s = "Hello world,C#!";
		int cnt = s.WordCount();
		Console.WriteLine(cnt);
	}
}
output:
3

Here, the stringobject is extended and WordCountmethods are added , but not stringadded inside the class, but a separate staticclass is ExtensionMethodStringdefined, which defines the staticmethod WordCount, and the first parameter ( stringtype) is preceded by a special this , Which shows that it is a special stringtype of extension method. The compiler will s.WordCount()automatically translate it into a ExtensionMethodString.WordCountcall.
The extension method is a very useful mechanism. It "adds" a method to the original without changing the definition of the original class, which is actually a kind of syntactic sugar.
The extension method was introduced from C#3.0, and one of its functions is to serve Linq. In Linq technology, the designers of .NET defined a series of extension methods in the class library to facilitate users to manipulate collection objects. These extension methods constitute Linq's query operators.

3.Linq's query operator

Linq's various query operators are actually System.Linq.Enumerablea series of extension methods defined in the class. These extension methods are extensions of IEnumerablepeer objects. So you can use var result = arr.Where(a => a > 3).Sum()this calling method to call.
Linq has more than 40 standard query operators, as shown in the following table. These methods have a small part can have equivalent query expression keywords, such as wherekeyword is equivalent to the Wheremethod, there are similar select, group, orderby, joinand so on.
Insert picture description here
From the perspective of execution time, each standard query operator can be divided into two categories, one is immediate execution, and the other is delayed execution. Methods that return a single value (such as Averageand Sum) will be executed immediately. The method of returning a sequence will delay the execution of the query, because it returns an enumerable ( IEnumerable) object, which will only be foreachexecuted when it is used to traverse or Sumperform operations again . It can also be said that there are two types of query operators. One type is "intermediate point" (such as Where), which can continue to apply other query operators; the other type is "finished" (such as Sum), and its results cannot be applied to other queries. Operator.
The following are commonly used operators and a brief introduction:
Where : Filter out those that meet the conditions.
Select : Take out the element (can be mapped to a new object).
First : Take out the first element of the sequence.
Take : Take out some elements.
Single : Take out the only element of the sequence. If the number of elements is not one, an error will be reported.
FirstOrDefault: Get the first element of the sequence, if there is no element, return the default value.
Distinct : Take out non-repeating elements in the sequence.
Orderby : sort.
Reverse : Reverse order.
Concat : Connect two sequences; equivalent to the Union all of SQL.
Contains : Whether the sequence contains the specified element.
Except : Obtain the difference of two sequences.
Intersect : Obtain the intersection of two sequences.
Average : Calculate the average value.
Min : The smallest element.
Max : The largest element.
Sum : the sum of elements.
Count : the number of elements.

Guess you like

Origin blog.csdn.net/qq_45349225/article/details/114335541