//用戶類 public class User { [DataMember] public int ID { get; set; } [DataMember] public string Name { get; set; } [DataMember] public string Address { get; set; } [DataMember] public string Phone { get; set; } [DataMember] public string Sex { get; set; } [DataMember] public int Age { get; set; } [DataMember] public int SchID { get; set; } } /// <summary> /// 學校類 /// </summary> internal class School { public int SchID { get; set; } public string SchName { get; set; } public School(){} public School(int id,string name) { SchID = id; SchName = name; } } /// <summary> /// 公司類 /// </summary> internal class Company { public string Name { get; set; } public List<User> Users { get; set; } public Company() { } public Company(string name, List<User> list) { Name = name; Users = list; } }
接下來初始化點測試數據
User user1 = new User() { ID = 111, Name = "張一", Address = "上海市某某區", Phone = "13547878787", Age = 30, Sex = "男", SchID=1 }; User user2 = new User() { ID = 112, Name = "李小二", Address = "上海市某某區", Phone = "13547878783", Age = 30, Sex = "女", SchID = 1 }; User user3 = new User() { ID = 113, Name = "張三", Address = "上海市某某區", Phone = "13547878784", Age = 30, Sex = "男", SchID = 1 }; User user4 = new User() { ID = 114, Name = "李四", Address = "上海市某某區", Phone = "13547878785", Age = 30, Sex = "男", SchID = 1 }; List<User> userlist = new List<User>(4) { user1, user2, user3, user4 }; List<School> Schlist = new List<School>() { new School(1,"武漢大學"),new School(2,"華中科技大學"),new School(3,"華中師范大學") };
統計(求和)Sum
//求和 var sum = userlist.Where(a => { return a.ID > 0; }).Sum(a=>a.ID); Console.WriteLine(sum); //另一種寫法 sum =(from a in userlist where a.ID>0 select a.ID ).Sum(); Console.WriteLine(sum); IEnumerable.Where()方法裡面的參數數委托類型Func<TSource, bool> 前面為參數 最後面一個為返回值
求最大最小值 Max Min //求最大值 var max = userlist.Max(a => a.ID); Console.WriteLine(max); //最小值 var min = userlist.Min(a => a.ID); Console.WriteLine(min); 循環 ForEach
//循環輸出 userlist.ForEach(a => { if (a.Age > 20) { Console.WriteLine(a.ID); } });
條件篩選 where //篩選 var user = userlist.Where(a => a.ID == 114).Single(); //篩選所有男性用戶 var templist = userlist.Where(a => a.Sex == "男").ToList(); 排序 //排序 根據ID逆序 templist = userlist.OrderByDescending(a => a.ID).ToList(); //升序 templist = userlist.OrderBy(a => a.ID).ToList(); 分組 ToLookup 和 GroupBy
//分組 var lookup = userlist.ToLookup(a => a.Sex); foreach (var item in lookup) { Console.WriteLine(item.Key); foreach (var sub in item) { Console.WriteLine("\t\t"+sub.Name+" "+sub.Age); } } //另一種 var dic = userlist.GroupBy(a => a.Sex); foreach (var item in dic) { Console.WriteLine(item.Key); foreach (var sub in item) { Console.WriteLine("\t\t" + sub.Name + " " + sub.Age); } }