【问题标题】:getting a specific string fields from a Generic List to an array从通用列表中获取特定字符串字段到数组
【发布时间】:2011-06-06 01:20:01
【问题描述】:

在c#中,假设我有一个如下类..

public class anItem
    {
        public string name { get; set; }
        public string surname { get; set; }
    }

我对那个对象使用一个通用列表,比如。

List<anItem> listof = new List<anItem>();
listof.Add(new anItem { name = "name 1", surname = "surname 1" });
listof.Add(new anItem { name = "name 2", surname = "surname 2" });
listof.Add(new anItem { name = "name 3", surname = "surname 3" });
listof.Add(new anItem { name = "name 4", surname = "surname 4" });

是否可以将 listof 通用列表中的所有 surname 都放到字符串数组中?

string[] takenSurnames = // take just surnames from listof

是的,我可以通过 foreachfor 循环来实现。但我想知道是否有任何 lambda 表达式或类似的更短的表达式?

提前谢谢..

【问题讨论】:

    标签: c# c#-4.0


    【解决方案1】:
    listof.Select(c => c.surename).ToArray();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-23
      • 2021-05-23
      • 2012-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      相关资源
      最近更新 更多