Lnaguage Intergrated Query(Linq) 集成查詢語言
基本查詢表達式模式來查詢和轉換 SQL 數據庫、ADO.NET 數據集、XML 文檔和流以及 .NET 集合中的數據
Linq語句的三個步驟:
1.定義數據源;
2.定義查詢語句;
3.執行查詢語句。
sample1
class LINQQueryExpressions
{
static void Main()
{
// 定義數據源
int[] scores = new int[] { 97, 92, 81, 60 };
// 定義查詢語句
IEnumerable scoreQuery =
from score in scores
where score > 80
select score;
// 執行查詢語句
foreach (int i in scoreQuery)
{
Console.Write(i + " ");
}
//執行query語句的其他方法
//scoreQuery.ToList();
//scoreQuery.ToArray();
}
}
query語句在沒有使用到這個數據集的時候,是沒有執行的,這里需要注意數據調用的先后順序。以免造成錯誤。
查詢兩種方法
query語句形式,方法的形式
query語句形式如sample1所示。
方法的形式
var ScoreQuery2=Scores where(score=>score>80)
order by(score=>score);
在上面的查詢中,用到的是int型數據這里轉換到string類型,代碼如下:
IEnumerable highScoresQuery2 =
from score in scores
where score > 80
orderby score descending
select String.Format("The score is {0}", score);
由於查詢存儲了結果,已經是一個元素集,在程序中不能將查詢變量單純看為一個變量。
select,group,into關鍵字
// percentileQuery is an IEnumerable>
var percentileQuery =
from country in countries
let percentile = (int) country.Population / 10000000
group country by percentile into countryGroup
where countryGroup.Key >= 20
orderby countryGroup.Key
select countryGroup;
// grouping is an IGrouping
foreach (var grouping in percentileQuery)
{
Console.WriteLine(grouping.Key);
foreach (var country in grouping)
Console.WriteLine(country.Name + ":" + country.Population);
}
where子句
IEnumerable queryCityPop =
from city in cities
where city.Population < 200000 && city.Population > 100000
select city;
orderby 子句
IEnumerable querySortedCountries =
from country in countries
orderby country.Area, country.Population descending
select country;
Join子句集合之間的連接,左連接,右連接。
var categoryQuery =
from cat in categories
join prod in products on cat equals prod.Category
select new { Category = cat, Name = prod.Name };
let子句
string[] names = { "Svetlana Omelchenko", "Claire O'Donnell", "Sven Mortensen", "Cesar Garcia" };
IEnumerable queryFirstNames =
from name in names
let firstName = name.Split(new char[] { ' ' })[0]
select firstName;
foreach (string s in queryFirstNames)
Console.Write(s + " ");
子查詢
var queryGroupMax =
from student in students
group student by student.GradeLevel into studentGroup
select new
{
Level = studentGroup.Key,
HighestScore =
(from student2 in studentGroup
select student2.Scores.Average())
.Max()
};