Lnaguage Intergrated Query(Linq) 集成查詢語言
基本查詢表達式模式來查詢和轉換 SQL 數據庫、ADO.NET 數據集、XML 文檔和流以及 .NET 集合中的數據數據庫
Linq語句的三個步驟:
1.定義數據源;
2.定義查詢語句;
3.執行查詢語句。c#
sample1code
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語句在沒有使用到這個數據集的時候,是沒有執行的,這裏須要注意數據調用的前後順序。以避免形成錯誤。orm
查詢兩種方法ci
query語句形式,方法的形式文檔
query語句形式如sample1所示。
方法的形式string
var ScoreQuery2=Scores where(score=>score>80) order by(score=>score);
在上面的查詢中,用到的是int型數據這裏轉換到string類型,代碼以下:it
IEnumerable highScoresQuery2 = from score in scores where score > 80 orderby score descending select String.Format("The score is {0}", score);
因爲查詢存儲告終果,已是一個元素集,在程序中不能將查詢變量單純看爲一個變量。io
select,group,into關鍵字class
// 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() };