【问题标题】:C# Select elements in list as List of stringC# 选择列表中的元素作为字符串列表
【发布时间】:2012-03-27 08:22:13
【问题描述】:

在 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 函数或一些较短的代码从列表对象属性值中提取值到一个字符串对象。

我的查询类似于C# select elements from IList,但我希望结果为字符串列表

【问题讨论】:

    标签: c# linq


    【解决方案1】:
    List<string> empnames = emplist.Select(e => e.Ename).ToList();
    

    这是Projection in Linq 的示例。后跟ToList 将IEnumerable&lt;string&gt; 解析为List&lt;string&gt;。

    或者在 Linq 语法中(头部编译):

    var empnamesEnum = from emp in emplist 
                       select emp.Ename;
    List<string> empnames = empnamesEnum.ToList();
    

    Projection 基本上是将可枚举的当前类型表示为新类型。您可以通过调用构造函数等投影到匿名类型、另一种已知类型,或其中一个属性的可枚举(如您的情况)。

    例如,您可以将Employee 的可枚举项投影到Tuple&lt;int, string&gt; 的可枚举项,如下所示:

    var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));
    

    【讨论】:

    • LINQ 的力量.. (约翰尼戏剧的声音)
    【解决方案2】:
    List<string> empnames = (from e in emplist select e.Enaame).ToList();
    

    或者

    string[] empnames = (from e in emplist select e.Enaame).ToArray();
    

    等等……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 2019-04-25
      • 2016-03-14
      • 1970-01-01
      • 2020-02-23
      • 2015-05-15
      • 2023-04-07
      • 1970-01-01
      相关资源
      最近更新 更多