C#选择列表中的元素作为字符串列表

Ram*_*Ram 41 c# linq

在C#中,我需要从对象列表中获取特定属性的所有值到字符串列表中

List<Employee> emplist = new List<Employee>()
                                {
                                 new Employee{ EID=10, Ename="John"},
                                 new Employee{ EID=11, Ename="Adam"},
                                 new Employee{ EID=12, Ename="Ram"}
                                };
List<string> empnames = emplist.//get all Enames in 'emplist' object into list
                         //using linq or list functions or IENumerable  functions
Run Code Online (Sandbox Code Playgroud)

我熟悉提取值的foreach方法,但我想知道它是否可能使用linq或IENumerable函数或一些较短的代码将列表对象属性值中的值提取到字符串对象中.

我的查询与IList中的C#select元素类似, 但我想将结果作为字符串列表

Ada*_*rth 93

List<string> empnames = emplist.Select(e => e.Ename).ToList();
Run Code Online (Sandbox Code Playgroud)

这是LinqProjection的一个例子.其次是一个ToList解决IEnumerable<string>成一个List<string>.

或者在Linq语法中(头编译):

var empnamesEnum = from emp in emplist 
                   select emp.Ename;
List<string> empnames = empnamesEnum.ToList();
Run Code Online (Sandbox Code Playgroud)

投影基本上将可枚举的当前类型表示为新类型.您可以通过调用构造函数等来投影到匿名类型,另一种已知类型,或者可以枚举其中一个属性(如您的情况).

例如,您可以将可枚举的项目Employee枚举为Tuple<int, string>如下:

var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));
Run Code Online (Sandbox Code Playgroud)

  • LINQ的力量.. <胜利!>(约翰尼戏剧的声音) (2认同)

Str*_*llo 10

List<string> empnames = (from e in emplist select e.Enaame).ToList();
Run Code Online (Sandbox Code Playgroud)

要么

string[] empnames = (from e in emplist select e.Enaame).ToArray();
Run Code Online (Sandbox Code Playgroud)

等等...