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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9885748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 11:04:50  来源:igfitidea点击:

C# Select elements in list as List of string

c#linq

提问by Ram

In C# i need to get all values of a particular property from an object list into list of string

在 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

I am familiar with the foreach method to extract the value but I want to know if \ how its possible use linq or IENumerable functionsor some shorter code to extract values from the list object property values into a string object.

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

My query is Similar to C# select elements from IListbut i want the the result as list of string

我的查询类似于C# 从 IList 中选择元素,但我希望结果为字符串列表

采纳答案by Adam Houldsworth

List<string> empnames = emplist.Select(e => e.Ename).ToList();

This is an example of Projection in Linq. Followed by a ToListto resolve the IEnumerable<string>into a List<string>.

这是Linq 中投影示例。后跟 aToList解析IEnumerable<string>成 a List<string>

Alternatively in Linq syntax (head compiled):

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

var empnamesEnum = from emp in emplist 
                   select emp.Ename;
List<string> empnames = empnamesEnum.ToList();

Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).

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

For example, you can project an enumerable of Employeeto an enumerable of Tuple<int, string>like so:

例如,您可以Employee将一个可枚举项投影到一个可枚举项,Tuple<int, string>如下所示:

var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));

回答by Strillo

List<string> empnames = (from e in emplist select e.Enaame).ToList();

Or

或者

string[] empnames = (from e in emplist select e.Enaame).ToArray();

Etc...

等等...