在 C# 中,我需要将对象列表中特定属性的所有值获取到字符串列表中
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 方法来提取值,但我想知道if \ 如何可能使用 linq 或 IEnumerable 函数或一些较短的代码,用于将列表对象属性值中的值提取到字符串对象中。
我的查询类似于C# 从 IList 中选择元素 https://stackoverflow.com/questions/2616891/c-sharp-select-elements-from-ilist但我想要结果作为字符串列表
List<string> empnames = emplist.Select(e => e.Ename).ToList();
这是一个例子Linq 中的投影 http://msdn.microsoft.com/en-us/library/bb738447.aspx。随后是一个ToList
来解决IEnumerable<string>
into a List<string>
.
或者使用 Linq 语法(头编译):
var empnamesEnum = from emp in emplist
select emp.Ename;
List<string> empnames = empnamesEnum.ToList();
投影基本上是将可枚举的当前类型表示为新类型。您可以通过调用构造函数等来投影到匿名类型、另一种已知类型,或者其中一个属性的可枚举类型(如您的情况)。
例如,您可以投影一个可枚举的Employee
到可枚举的Tuple<int, string>
像这样:
var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)