語言集成查詢 (LINQ) 不僅可用於檢索數據, 而且還是一個功能強大的數據轉換工具。 通過使用 LINQ 查詢,您可以將源序列用作輸入,並采用多種方式修改它以創建新的輸出序列。您可以通過排序和分組來修改該序列,而不必修改元素本身。但是,LINQ 查詢的最強大的功能是能夠創建新類型。這一功能在 select 子句中實現。 例如,可以執行下列任務:
1 class Student 2 { 3 public string Name { get; set; } 4 5 public int Age { get; set; } 6 7 public string City { get; set; } 8 9 public List<int> Scores { get; set; } 10 } 11 12 class Teacher 13 { 14 public int Id { get; set; } 15 16 public string Name { get; set; } 17 18 public int Age { get; set; } 19 20 public string City { get; set; } 21 22 } 學生和老師兩個類
1 internal class Program 2 { 3 private static void Main(string[] args) 4 { 5 //創建第一個數據源 6 var students = new List<Student>() 7 { 8 new Student() 9 { 10 Age = 23, 11 City = "廣州", 12 Name = "小C", 13 Scores = new List<int>(){85,88,83,97} 14 }, 15 new Student() 16 { 17 Age = 18, 18 City = "廣西", 19 Name = "小明", 20 Scores = new List<int>(){86,78,85,90} 21 }, 22 new Student() 23 { 24 Age = 33, 25 City = "夢裡", 26 Name = "小三", 27 Scores = new List<int>(){86,68,73,97} 28 } 29 }; 30 31 //創建第二個數據源 32 var teachers = new List<Teacher>() 33 { 34 new Teacher() 35 { 36 Age = 35, 37 City = "夢裡", 38 Name = "啵哆" 39 }, 40 new Teacher() 41 { 42 Age = 28, 43 City = "雲南", 44 Name = "小紅" 45 }, 46 new Teacher() 47 { 48 Age = 38, 49 City = "河南", 50 Name = "麗麗" 51 } 52 }; 53 54 //創建查詢 55 var peopleInDreams = (from student in students 56 where student.City == "夢裡" 57 select student.Name) 58 .Concat(from teacher in teachers 59 where teacher.City == "夢裡" 60 select teacher.Name); 61 62 //執行查詢 63 foreach (var person in peopleInDreams) 64 { 65 Console.WriteLine(person); 66 } 67 68 Console.Read(); 69 } 70 }
1. 若要只選擇源元素的一個成員,請使用點運算。
1 var query = from cust in Customers 2 select cust.City;
2. 若要創建包含源元素的多個屬性的元素,可以使用具有命名對象或匿名類型的對象初始值設定項。
1 var query = from cust in Customer 2 select new {Name = cust.Name, City = cust.City};
1 //創建數據源 2 var students = new List<Student>() 3 { 4 new Student() 5 { 6 Age = 18, 7 Name = "小A", 8 Scores = new List<int>() {88,85,74,66 } 9 }, 10 new Student() 11 { 12 Age = 35, 13 Name = "小B", 14 Scores = new List<int>() {88,85,74,66 } 15 }, 16 new Student() 17 { 18 Age = 28, 19 Name = "小啥", 20 Scores = new List<int>() {88,85,74,66 } 21 } 22 }; 23 24 //創建查詢 25 var studentsToXml = new XElement("Root", 26 from student in students 27 let x = $"{student.Scores[0]},{student.Scores[1]},{student.Scores[2]},{student.Scores[3]}" 28 select new XElement("student", 29 new XElement("Name", student.Name), 30 new XElement("Age", student.Age), 31 new XElement("Scores", x)) 32 ); 33 34 //執行查詢 35 Console.WriteLine(studentsToXml);
輸出序列可能不包含源序列的任何元素或元素屬性。輸出可能是通過將源元素用作輸入參數計算出的值的序列。
1 //數據源 2 double[] radii = {1, 2, 3}; 3 4 //創建查詢 5 var query = from radius in radii 6 select $"{radius * radius * 3.14}"; 7 8 //執行查詢 9 foreach (var i in query) 10 { 11 Console.WriteLine(i); 12 }
【來源】本文文字主要來自微軟官方文檔