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

编程入门 行业动态 更新时间:2024-10-27 15:25:34
本文介绍了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#中选择列表中的元素作为字符串列表

本文发布于:2023-11-24 08:31:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1624481.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   元素   列表   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!