A common keyword of Linq.
Directory
Preface
Series of articles
Common keywords
Summary
Preface
The previous articles pave the way for the use of linq. From the beginning of this article, we will introduce the syntax and practices of linq.
Series of articles
A preliminary understanding of Lambda expressions in Linq
Lambda of Linq (advanced tutorial)
Implicit type, automatic attribute, initializer, and Anonymous class of Linq
Extended method of Linq
First Appearance of Expression of Linq
Expression IN Linq (advanced tutorial)
Expression of Linq (common Expression types)
Common keywords
Under what circumstances should I use linq?
As you can say, any object that implements the IEnumerable <T> interface can be queried using the Linq syntax.
For objects that only implement the IEnumerable interface but not the IEnumerable <T>, you can use the following method:
public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source);
To convert the IEnumerable interface to IEnumerable <T> (for example, ArrayList ).
What are the common keywords in linq?
In c #3.0, several keywords are introduced for linq: from join where group into let orderby select.
If you have used SQL, you are no stranger to them. The syntax is very simple. Here we will list an example for each simple example so that you can quickly recall their usage.
From
The from clause is the start of a Linq query. Any Linq statement starts with from. The from clause specifies the query container and the local variables valid for this statement. The syntax of the from clause is:
from localParameter in Source
From the above syntax, you will find that it is similar to foreach.
Foreach (var item in source) {// loop body}
Through the comparison above, you should have a clear understanding of localParameter and Source. However, in linq, Source must be an object that implements IEnumerable <T>. The following is an example:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 List<int> lstInts = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 6 IEnumerable<int> query = from i in lstInts 7 select i; 8 foreach (var item in query) 9 {10 Console.WriteLine(item);11 }12 Console.Read();13 }14 }
Result
The example has no practical significance. Through this example, we hope to have a rough understanding of linq. Because source is implemented from IEnumerable <T> generic interface, T can be derived from source. In this example, T is int.
So how to use linq for the ArrayList that does not implement IEnumerable <T> but only implements the IEnumerable interface?
In this case, we need to explicitly specify the type of the local variable, or use Cast to convert to IEnumerable <T>
For example:
1 IEnumerable <int> q2 = from I in arry. Cast <int> () 2 select I; 3 // or 4 var q3 = from int I in arry5 select I;
Select
Projection of the query results. Sometimes we don't need all the columns, but only the values of some of them. In this case, select is very useful.
The following is an example.
Suppose we have such a class
1 class Person2 {3 public int ID { set; get; }4 public string Name { set; get; }5 public int Age { set; get; }6 }
We have such a set
1 List<Person> persons = new List<Person>() 2 {3 new Person(){ ID=1, Age=20, Name="wolfy"},4 new Person(){ID=2,Age=22,Name="angle"}5 };
Now we need to retrieve the names of all users in the set, that is, only one column is projected.
1 var pNames = from p in persons2 select p.Name;
Of course, we can also project a set. In this case, we need to use an anonymous class.
1 var persons2 = from p in persons2 select new {p. name, p. age}; 3 // or 4 var persons3 = from p in persons5 select new {name = p. name, age = p. age}; 6 foreach (var item in persons3) 7 {8 Console. writeLine (item. name + "" + item. age); 9}
In persons3, you can display the name of the specified projection column in the anonymous class.
Where
Filter the data in source. Let's look at an example and select the names of all adults.
var persons4 = from p in persons where p.Age > 18 select p.Name;
Join
Similar to join in SQL, two sources are associated in a certain relationship.
For example, find out the name of the person in the company "Beijing capability Co., Ltd." and the name of the company.
1 class Person 2 { 3 public int ID { set; get; } 4 public string Name { set; get; } 5 public int Age { set; get; } 6 public int CompanyID { set; get; } 7 } 8 class Company 9 {10 public int ID { set; get; }11 public string Name { set; get; }12 }
1 List <Person> persons = new List <Person> () 2 {3 new Person () {ID = 1, Age = 20, Name = "wolfy ", companyID = 1}, 4 new Person () {ID = 2, Age = 22, Name = "angle", CompanyID = 2} 5 }; 6 List <Company> companys = new List <Company> () 7 {8 new Company () {ID = 1, Name = "Beijing capability Co., Ltd "}, 9 new Company () {ID = 2, Name = "Beijing incompetent Company Limited"} 10}; 11 var result = from p in persons12 join c in companys on p. companyID equals c. ID13 where c. name = "Beijing capability Co., Ltd." 14 select new {Name = p. name, CompanyName = c. name}; 15 foreach (var item in result) 16 {17 Console. writeLine (item. name + "" + item. companyName); 18}
Result
Note:
The join clause can only use equals or not equal, but cannot use other operators (= ). The left part of the equals operator must be connected, and the right part cannot be changed. Otherwise, compilation cannot pass.
Into and group
The into clause is used to continue the results of join or group clauses and encapsulate them into a System. linq. IGrouping <TKey, TElement> object, and IGrouping inherits from IEnumerable <TElement>. The IGrouping interface provides the grouping key and the set contained in the key.
The following is an example.
1 List<string> lstNames = new List<string>() { "zhangsan", "lisi", "wanger", "mazi", "zhangwuji" }; 2 var result2 = from n in lstNames 3 group n by n.Length into g 4 select new { g.Key, values = g }; 5 foreach (var group in result2) 6 { 7 Console.WriteLine("{0}:", group.Key); 8 foreach (var item in group.values) 9 {10 Console.WriteLine(item);11 }12 }
Result
Let
The let clause is used to add a new local variable to the query to make it visible in the subsequent query. For example, the as keyword in SQL is used as the field alias.
1 var persons4 = from p in persons2 let age = p.Age3 where age > 184 select p.Name;
Take Skip
Used to select the first few or to skip the first few. For example, if you select 11th to 20, you can
1 query.Skip(10).Take(10);
Skip the first 10 and then fetch 10 more data records.
OrderBy OrderByDescending
query.OrderBy(c => c.Length);
Summary
This article introduces the common keywords in linq. Their functions can be analogous to the usage in SQL. Of course, there are some keywords, such as Distinct Union Intersect Except T, which will not be used as an example. If you are interested, try it yourself.
Other sample code can be referred to: https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
References
Http://kb.cnblogs.com/page/100043/