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

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

问题描述

在C#我需要从一个对象列表中的特定属性的所有值转换成字符串列表



 列表<员工> ; emplist =新的List<员工>()
{
新员工{EID = 10,为ename =约翰},
新员工{EID = 11,为ename =亚当},
新员工{EID = 12,为ename =拉姆}
};
名单,LT;字符串> empnames = emplist.//get所有Enames在emplist'对象为列表
//使用LINQ或列表功能或IEnumerable的函数

我所熟悉的在foreach方法提取的价值,但我想知道如果\如何其可能使用LINQ或功能的IEnumerable 或一些短代码来提取值从列表对象属性值转换成字符串对象。



我的查询是的自IList C#中选择元素,但我想要的结果作为字符串


解决方案

 列表<串GT; empnames = emplist.Select(E => e.Ename).ToList(); 

这是的投影Linq中。随之而来的是了ToList 来解决的IEnumerable<串> 列表<串>



另外在LINQ的语法(头编译):

  VAR empnamesEnum =从emplist 
EMP选择emp.Ename;
名单,LT;字符串> empnames = empnamesEnum.ToList();



投影基本上是代表当前类型的枚举作为新类型。你可以通过调用构造函数等,或性质之一的枚举(如你的情况)投影到匿名类型,另一种已知类型。



例如,你可以项目员工的枚举到元组LT的枚举,整型,字符串> 像这样:

  VAR元组= emplist.Select(E =>新建元组LT; INT,串>(e.EID,e.Ename)); 


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

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.

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();

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

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).

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天全站免登陆