標籤:logs xtend -- 測試 ring each lin class ons
1.需要一個資料來源類:
using System;using System.Collections.Generic;namespace Linq{ public class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } public class Data { public static List<Student> studentList = new List<Student>() { new Student() { Name="李四", Age=18 }, new Student() { Name="張三", Age=20 } }; }}
2.主函數調用類
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Linq{ class Program { static void Main(string[] args) { LinqTest lin = new LinqTest(); lin.Show(); } }}
3.查詢方法(重點介紹的)
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Linq{ public class LinqTest { public void Show() { List<Student> studentList = new List<Student>();// Console.WriteLine("-----------------foreach方式(1)---------"); foreach (Student item in Data.studentList) ////Data.studentList是資料來源 { if (item.Age > 18) { studentList.Add(item);//將資料來源中滿足要求的資料填充到指定容器中 } } //studentList中以填充資料 foreach (Student item in studentList) { Console.WriteLine("foreach方式:Name={0},Age={1}", item.Name, item.Age); } Console.WriteLine("-----------linq方式(2)-------------"); var linq = from s in Data.studentList where s.Age > 18 select s; foreach (var item in linq) { Console.WriteLine("linq方式:Name={0},Age={1}", item.Name, item.Age); } Console.WriteLine("-----------lambda方式(3)-------------"); // var lambda = Data.studentList.Where(s => s.Age > 18); where可以自動推斷類型 擴充方法 var lambda = Data.studentList.Where<Student>(s => s.Age > 18); foreach (var item in lambda) { Console.WriteLine("lambda方式:Name={0},Age={1}", item.Name, item.Age); } Console.WriteLine("-------Enumerable靜態類方式(4)-----------"); var enm= Enumerable.Where(Data.studentList, s => s.Age > 18); foreach (var item in enm) { Console.WriteLine("Enumerable靜態類方式:Name={0},Age={1}", item.Name, item.Age); } } }}
(3.1)對where擴充方法的理解即學習
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Linq{ public class LinqTest { public void Show() { Console.WriteLine("-----------lambda方式(3.1)where擴充-------------"); var linqExtend = Data.studentList.WhereExtend(s => s.Age > 18); //where可以自動推斷類型 擴充方法 foreach (var item in linqExtend) { Console.WriteLine("lambda方式(3.1)where擴充:Name={0},Age={1}", item.Name, item.Age); } } } /// <summary> /// where的擴充方法 /// </summary> public static class LinqExtend { public static IEnumerable<T> WhereExtend<T>(this IEnumerable<T> tList,Func<T,bool> func) where T : Student// func:用於測試每個元素是否滿足條件的函數。 { var Linq = from s in tList where func(s) select s; return Linq; } }}
幾種查詢方法(lambda Linq Enumerable靜態類方式)