使用LINQ获取列表中的某个字段值,下面以获取员工列表中的编号字段为例子。
1、使用Select方法
1 List<Emplayee> emplayeeList = GetEmplayeeList(); //获取员工信息列表 2 int[] empIds = emplayeeList.Select(a => a.Id).ToArray(); //获取员工编号数组
2、使用ForEach方法
1 List<Emplayee> emplayeeList = GetEmplayeeList(); //获取员工信息列表 2 string empIds = ""; 3 emplayeeList.ForEach(a => empIds += a.Id + ","); 4 empIds = empIds.TrimEnd(','); 5 Console.WriteLine(empIds); //输出:1,2,3
辅助代码:
1 /// <summary> 2 /// 员工信息类 3 /// </summary> 4 public class Emplayee 5 { 6 /// <summary> 7 /// 编号 8 /// </summary> 9 public int Id { get; set; } 10 11 /// <summary> 12 /// 姓名 13 /// </summary> 14 public string Name { get; set; } 15 } 16 17 18 /// <summary> 19 /// 获取员工信息列表 20 /// </summary> 21 /// <returns></returns> 22 public static List<Emplayee> GetEmplayeeList() 23 { 24 List<Emplayee> emplayeeList = new List<Emplayee>(); 25 Emplayee emplayee1 = new Emplayee() { Id = 1, Name = "张三" }; 26 Emplayee emplayee2 = new Emplayee() { Id = 2, Name = "李四" }; 27 Emplayee emplayee3 = new Emplayee() { Id = 3, Name = "王五" }; 28 emplayeeList.Add(emplayee1); 29 emplayeeList.Add(emplayee2); 30 emplayeeList.Add(emplayee3); 31 return emplayeeList; 32 }