使用LINQ获取列表中的某个字段值,下面以获取员工列表中的编号字段为例子。
1、使用Select方法
List<Emplayee> emplayeeList = GetEmplayeeList(); //获取员工信息列表
int[] empIds = emplayeeList.Select(a => a.Id).ToArray(); //获取员工编号数组
2、使用ForEach方法
List<Emplayee> emplayeeList = GetEmplayeeList(); //获取员工信息列表
string empIds = "";
emplayeeList.ForEach(a => empIds += a.Id + ",");
empIds = empIds.TrimEnd(',');
Console.WriteLine(empIds); //输出:1,2,3
其它代码:
/// <summary>
/// 员工信息类
/// </summary>
public class Emplayee
{
/// <summary>
/// 编号
/// </summary>
public int Id { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
}
/// <summary>
/// 获取员工信息列表
/// </summary>
/// <returns></returns>
public static List<Emplayee> GetEmplayeeList()
{
List<Emplayee> emplayeeList = new List<Emplayee>();
Emplayee emplayee1 = new Emplayee() { Id = 1, Name = "张三" };
Emplayee emplayee2 = new Emplayee() { Id = 2, Name = "李四" };
Emplayee emplayee3 = new Emplayee() { Id = 3, Name = "王五" };
emplayeeList.Add(emplayee1);
emplayeeList.Add(emplayee2);
emplayeeList.Add(emplayee3);
return emplayeeList;
}