記錄LINQ學習程序,
概要
LINQ是一種“語言集成”的查詢運算式,使用LINQ可以智能提示和進行型別檢查,C#里可以撰寫的LINQ查詢有SQL資料庫、XML檔案、ADO.NET資料集、支持IEnumerable和IEnumerable的物件,使用LINQ,可以簡單對資料源進行分組、排序、篩選,有一些第三方庫也為Web服務和其他資料庫提供了LINQ支持,
陣列隱式支持了 IEnumerable 介面的,
//尚未執行查詢,等待遍歷再查, 可以在查詢運算式后面添加ToList或ToArray方法,使之立刻查詢,
IEnumerable<int> scoreQuery =
from score in new int[] { 97, 92, 81, 60 }
where score > 90
select score;
在編譯時,查詢運算式根據 “C# 規范規則”轉換成“標準查詢運算子方法呼叫”,
在撰寫 LINQ 查詢時最好使用查詢語法,必要時可以使用方法呼叫,
查詢簡介
要想查詢,資料源必須在記憶體中,
//LINQ to XML 將 XML 檔案加載到可查詢的 XElement 型別中: XElement contacts = XElement.Load(@"c:\myContactList.xml"); //LINQ to SQL ,可以手動設計物件關系映射或借助LINQ TO SQL工具
LINQ和泛型
LINQ引入泛型機制,泛型屬于強型別,不必執行運行時型別轉換,與Object相比,優勢更多,
編譯器可以處理泛型型別宣告,因此可以通過var關鍵字避免使用泛型語法,在LINQ里,是否顯示指定型別并不重要時,例如LINQ分組查詢之后的指定嵌套泛型型別,建議使用var,畢竟晦澀難懂的代碼不太招人喜歡喔!
LINQ基本查詢
篩選,排序
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
IEnumerable<Customer> customers = new List<Customer>() {
new Customer(){Name="David M. Buss" , City="美國奧斯汀"},
new Customer(){Name="David M. Buss 1" , City="美國奧斯汀"},
new Customer(){Name="David M. Buss 2" , City="美國奧斯汀"},
new Customer(){Name="阿爾弗雷德·阿德勒" , City="英國阿伯丁"},};
var queryUSCustomers =
from customer in customers
where customer.City == "美國奧斯汀"
orderby customer.Name ascending
select customer;
foreach(var customer in queryUSCustomers)
{
Console.WriteLine(customer.Name);
}
}
}
class Customer
{
public string Name { get; set; }
public string City { get; set; }
}
}
David M. Buss
David M. Buss 1
David M. Buss 2
分組
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
IEnumerable<Customer> customers = new List<Customer>() {
new Customer(){Name="David M. Buss" , City="美國奧斯汀"},
new Customer(){Name="David M. Buss 1" , City="美國奧斯汀"},
new Customer(){Name="David M. Buss 2" , City="美國奧斯汀"},
new Customer(){Name="阿爾弗雷德·阿德勒" , City="英國阿伯丁"},};
// queryCustomersByCity is an IEnumerable<IGrouping<string, Customer>>
var queryCustomersByCity =
from cust in customers
group cust by cust.City; //key 就是City
// customerGroup is an IGrouping<string, Customer>
//分組型別實作了IEnumerable介面
foreach (var customerGroup in queryCustomersByCity)
{
Console.WriteLine(customerGroup.Key);
foreach (Customer customer in customerGroup)
{
Console.WriteLine($" {customer.Name}");
}
}
}
}
class Customer
{
public string Name { get; set; }
public string City { get; set; }
}
}
關聯
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
IEnumerable<Customer> customers = new List<Customer>() {
new Customer(){Name="David M. Buss" , City="美國奧斯汀"},
new Customer(){Name="David M. Buss 1" , City="美國奧斯汀"},
new Customer(){Name="阿爾弗雷德·阿德勒" , City="英國阿伯丁"},};
IEnumerable<City> cities = new List<City>() {
new City(){Country="美國",CityName="美國奧斯汀"},
new City(){Country="英國",CityName="英國阿伯丁"},
};
var innerJoinQuery =
from cust in customers
join city in cities on cust.City equals city.CityName
select new { Country = city.Country, Customer = cust.Name };
//匿名型別
foreach (var item in innerJoinQuery)
{
Console.WriteLine($"{item.Country},{item.Customer}");
}
}
}
class Customer
{
public string Name { get; set; }
public string City { get; set; }
}
class City
{
public string Country { get; set; }
public string CityName { get; set; }
}
}
使用LINQ進行資料轉換
可以對原序列修改,可以在回傳值創建新型別,
//Concat合并序列
var peopleInSeattle = (from student in students
where student.City == "Seattle"
select student.Last)
.Concat(from teacher in teachers
where teacher.City == "Seattle"
select teacher.Last);
//記憶體中資料結構轉換為xml
var studentsToXML = new XElement("Root",
from student in students
let scores = string.Join(",", student.Scores) //存盤子運算式的結果
select new XElement("student",
new XElement("First", student.First),
new XElement("Last", student.Last),
new XElement("Scores", GetScore(scores)) //呼叫C#方法
) // end "student"
); // end "Root"
支持LINQ的C#功能
string[] stringArray = { "aa", "bb", "b", "a" }; var query = from str in stringArray group str by str[0] into stringGroup orderby stringGroup.Key select stringGroup; foreach (var item in query) { Console.WriteLine($"key:{item.Key }"); foreach (var item1 in item) { Console.WriteLine(item1); } } //不顯示呼叫建構式的初始化 var cust = new Customer { Name = "Mike", Phone = "555-1212" }; var IncomingOrders = new List<IncomingOrder>(); var newLargeOrderCustomers = from o in IncomingOrders where o.OrderSize > 5 select new Customer { Name = o.Name, Phone = o.Phone }; //等效的方法呼叫 var newLargeOrderCustomers1 = IncomingOrders.Where(o => o.OrderSize > 5) .Select(y => new Customer { Name = y.Name, Phone = y.Phone });
查詢運算式、var、不顯示呼叫建構式的初始化、匿名型別、擴展方法、lambda運算式,
用C#撰寫查詢LINQ
namespace ConsoleApp4 { class Program { static void Main(string[] args) { // studentQuery2 is an IEnumerable<IGrouping<char, Student>> IEnumerable<Student> students = new List<Student> { new Student{Last="aa",First="AA"}, new Student{Last="bb",First="BB"}, new Student{Last="bcc",First="BCC"} }; //創建查詢 var studentQuery= from student in students group student by student.Last[0]; //執行查詢 foreach(var item in studentQuery) { Console.WriteLine($"key:{item.Key}"); foreach(var item1 in item) { Console.WriteLine(item1.Last); } }
//使用let引入識別符號
var studentQuery5 =
from student in students
let totalScore = student.Scores[0] + student.Scores[1]
where totalScore / 4 < student.Scores[0]
select student.Last + " " + student.First; } } public class Student { public string Last { get; set; } public string First { get; set; } } }
運行結果:
key:a
aa
key:b
bb
bcc
使用 let 關鍵字,可以存盤運算式結果,存盤結果可以提供方便,也可以避免多次計算來提高性能,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/68916.html
標籤:C#
上一篇:C# Action 委托
下一篇:C# 最簡單的鏈式呼叫例子
