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 arr
to 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 int
the 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:
As you can see from the above example, the Linq
query syntax is very similar to the SQL query syntax, but it should be from
put in front, so that the type of the variable can be inferred, and it is convenient for the integrated development environment to perform intellisence.
Linq
The result of the query returns an enumerator object, which implements the IEnumerable
interface. The type of this object is generally very complex. It var
is represented by a type, and the compiler automatically infers its type. This var
object can be used foreach
to traverse. Linq
The result of some queries is a "queryable object" that implements an IQuerable
interface. Since the IQuerable
interface is IEnumerable
a sub-interface of the interface, more complex operations can be performed on it.
Worthy of note are: the enumerator var
object and does not really begin query, use only when foreach
the 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:
In this example, length
the data is grouped according to the character length ( ) ( group
) and put into the lengthGroups
variable, and sorted by the grouping keyword ( .Key
). The resulting enumerator is foreach
traversed in a double loop.
Linq's query method
About 40 defines Linq query operators, such as select
, from
, in
, where
and orderby
the 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.Enumerable
the 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 Where
extension method, which needs to pass in a Func<int, bool>
type of generic delegate, which means to int
judge an element ( variable of the type) ( a > 3
), and the return value is the bool
type. Here is the direct a => a > 3
transfer this Lambda expressions to the Where
method.
The other is the Sum
extension method, which calculates the sum of Where
the collection returned by the extension method.
Using the where
equal clause actually calls the Enumerable
extension method defined in the class.
2. Extension method
The so-called "extension methods" here are static
global functions defined in the class. It can take this
parameters, 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 string
object is extended and WordCount
methods are added , but not string
added inside the class, but a separate static
class is ExtensionMethodString
defined, which defines the static
method WordCount
, and the first parameter ( string
type) is preceded by a special this , Which shows that it is a special string
type of extension method. The compiler will s.WordCount()
automatically translate it into a ExtensionMethodString.WordCount
call.
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.Enumerable
a series of extension methods defined in the class. These extension methods are extensions of IEnumerable
peer 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 where
keyword is equivalent to the Where
method, there are similar select
, group
, orderby
, join
and so on.
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 Average
and 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 foreach
executed when it is used to traverse or Sum
perform 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.