Concept: "Query" is also a command set of instructions can be used to retrieve data from a given one or more data sources, and returns the result in the form of instructions. Linq is also a query, can provide a powerful and convenient search function is a programming language, and its combined into one.
The power of Linq in the amount of code it is simple and convenient. For example, to filter out the list of attributes in an element, relative to the list will traverse the judgment; but you only need to use linq sentence. But it can also cause some problems, leading to the latter than people cause trouble maintaining your project (how best thing ah, double-edged sword haha)
From: Clause queried data source (for loop equivalent)
Where: Clause filter elements satisfy the specified conditions (corresponding to the if)
orderby: expression (equivalent to sorting, ascending, descending ...)
Select: clause develop forms of query results, (equivalent to return)
Use the following code to illustrate the problem:
// Linq Query statement
int[] numbers = { 12, 23, 34, 45, 56, 67 };
var numQuery = from num in numbers
where num % 2 == 0
orderby num ascending // ascending 升序(可省略)
select num;
foreach(var n in numQuery)
{
Console.WriteLine(n);
}
// Linq Method Statement
var numMethod = numbers.Where(n => n % 2 == 0).OrderBy(n => n);
foreach(var n in numMethod)
{
Console.WriteLine(n);
}
Note: The above code amount difference between the two statements is a little big, Query separating each logic, all logical Method concentrate on the line to achieve.
into, let keyword
// Linq into keyword
List<Peo> peoList = new List<Peo>();
peoList.Add(new Peo() { name = "lizhi", city = "shanghai" });
peoList.Add(new Peo() { name = "linqingxia", city = "beijing" });
peoList.Add(new Peo() { name = "liuyifei", city = "shanghai" });
var intoLinq = from num in peoList
group num by num.city into groupnum
where groupnum.Count() >= 2
select new { city = groupnum.Key, number = groupnum.Count() };
foreach(var i in intoLinq)
{
Console.WriteLine(i.city + "---" + i.number);
}
Example above: into literally means "driving", the above examples will traverse num proList obtained groupnum screened into the city properties, groupnam herein may be considered as a collection, the collection is stored city properties.
// Linq let keyword
string[] strings = { "hello world.", "lin qing xia", "wang zu xian" };
var strs = from s in strings
let words = s.Split(' ')
from word in words
let w = word.ToUpper()
select w;
foreach(var s in strs)
{
Console.WriteLine(s);
}
Example above: The traversal processing elements, and the results stored into words, words can also be considered here is a collection (it can be understood, to discover their own particular Hey)