在 C# 中,我需要将特定属性的所有值从对象列表中获取到字符串列表中
In C# i need to get all values of a particular property from an object list into list of string
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我熟悉提取值的 foreach 方法,但我想知道 如果它如何可能使用 linq 或 IENumerable 函数 或一些较短的代码从列表对象属性值中提取值到一个字符串对象.
I am familiar with the foreach method to extract the value but I want to know if how its possible use linq or IENumerable functions or some shorter code to extract values from the list object property values into a string object.
我的查询类似于 C# 从 IList 中选择元素 但我想要结果为字符串列表
My query is Similar to C# select elements from IList but i want the the result as list of string
推荐答案 List<string> empnames = emplist.Select(e => e.Ename).ToList();这是 Linq 中的投影 的示例.后跟一个 ToList 将 IEnumerable 解析为 List.
This is an example of Projection in Linq. Followed by a ToList to resolve the IEnumerable<string> into a List<string>.
或者在 Linq 语法中(头部编译):
Alternatively in Linq syntax (head compiled):
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).
例如,您可以将 Employee 的枚举映射到 Tuple 的枚举,如下所示:
For example, you can project an enumerable of Employee to an enumerable of Tuple<int, string> like so:
var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));更多推荐
C#选择列表中的元素作为字符串列表
发布评论