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

编程入门 行业动态 更新时间:2024-10-27 05:26:30
本文介绍了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 中的投影 的示例.后跟一个 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#选择列表中的元素作为字符串列表

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

发布评论

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

>www.elefans.com

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