IEnumerable 相关操作
1 public class Employee 2 { 3 public int EmployeeID { get; set; } 4 public string Name { get; set; } 5 public string Sex { get; set; } 6 7 public int Age { get; set; } 8 public int salary { get; set; } 9 10 11 public override string ToString() 12 { 13 return $"{this.EmployeeID}-{Name}-{ Sex}-{ Age}-{ salary}"; 14 } 15 16 17 }
1.groupby
List<Employee> employees = new List<Employee>(); employees.Add(new Employee { EmployeeID = 100001, Name = "Lily", Age = 25, salary = 3500, Sex = "女" }); employees.Add(new Employee { EmployeeID = 100002, Name = "lucy", Age = 29, salary = 5500, Sex = "女" }); employees.Add(new Employee { EmployeeID = 100003, Name = "Jonth", Age = 35, salary = 4500, Sex = "男" }); employees.Add(new Employee { EmployeeID = 100004, Name = "tom", Age = 38, salary = 3900, Sex = "男" }); employees.Add(new Employee { EmployeeID = 100005, Name = "jerry", Age = 35, salary = 4700, Sex = "女" }); employees.Add(new Employee { EmployeeID = 100006, Name = "李四", Age = 44, salary = 7800, Sex = "男" }); employees.Add(new Employee { EmployeeID = 100007, Name = "王五", Age = 55, salary = 8100, Sex = "男" }); employees.Add(new Employee { EmployeeID = 100008, Name = "王二", Age = 46, salary = 6700, Sex = "男" }); IEnumerable<IGrouping<string, Employee>> items = employees.GroupBy(e => e.Sex); foreach (IGrouping<string, Employee> g in items) { Console.WriteLine(g.Key); //输出排序关键字 foreach(Employee e in g) { Console.WriteLine(e); //调用 Employee toString()方法 } }
输出 :女
100001-Lily-女-25-3500
100002-lucy-女-29-5500
100005-jerry-女-35-4700
男
100003-Jonth-男-35-4500
100004-tom-男-38-3900
100006-李四-男-44-7800
100007-王五-男-55-8100
100008-王二-男-46-6700
2.映射成新类型
即将原来集合List对象映射,匿名类型或 新类型的 List ,下面将employees 列表中的 Name,Sex,Age,Salary映射到新集合中
IEnumerable<dynamic> list = employees.Where(t => t.salary >= 5000).Select(t =>new { xm=t.Name,xb=t.Sex,nl=t.Age,gz=t.salary }); string s = ""; foreach (var item in list) { s = s + item; }
输出结果:
{ xm = lucy, xb = 女, nl = 29, gz = 5500 }{ xm = 李四, xb = 男, nl = 44, gz = 7800 }{ xm = 王五, xb = 男, nl = 55, gz = 8100 }{ xm = 王二, xb = 男, nl = 46, gz = 6700 }
3.分类汇总统计 Groupby
1 var lists= employees.GroupBy(e => e.Sex).Select(t => new { 性别 = t.Key, 最高工资 = t.Max(e=>e.salary),最低工资=t.Min(e=>e.salary) ,人数=t.Count()}); 2 string d = ""; 3 foreach (var item in lists) 4 { 5 d=d + item; 6 } 7 8 return Content( d);
输出:{ 性别 = 女, 最高工资 = 5500, 最低工资 = 3500, 人数 = 3 }{ 性别 = 男, 最高工资 = 8100, 最低工资 = 3900, 人数 = 5 }
4.自定义MySelect
static class my{ public static IEnumerable<dynamic> MySelect(this IEnumerable<Employee> list, Func<Employee, dynamic> f) { List<dynamic>ml= new List<dynamic>(); foreach (Employee e in list) { var t = f(e); ml.Add(t); } return ml; } }
var tlist= employees.Where(t=>t.Age>35).MySelect(t => new { xb = t.Sex, xm = t.Name, bh = t.EmployeeID,nl=t.Age }); string m = ""; foreach (var item in tlist) { m=m+item; } Console.WriteLine(m);