C#选择列表中的元素作为字符串列表 [英] C# Select elements in list as List of string

查看:34
本文介绍了C#选择列表中的元素作为字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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 中的投影 的示例.后跟一个 ToListIEnumerable 解析为 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#选择列表中的元素作为字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆