[英]C# Select elements in list as List of string
在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方法,但我想知道它是否可能使用linq或IENumerable函數或一些較短的代碼將列表對象屬性值中的值提取到字符串對象中。
我的查詢與IList中的C#select元素類似,但我想將結果作為字符串列表
List<string> empnames = emplist.Select(e => e.Ename).ToList();
這是Linq中Projection的一個例子。 接着是ToList
,將IEnumerable<string>
解析為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));
List<string> empnames = (from e in emplist select e.Enaame).ToList();
要么
string[] empnames = (from e in emplist select e.Enaame).ToArray();
等等...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.