仅包含一个类成员的创建列表

时间:2012-06-22 13:43:49

标签: c# list

我有这个班级的清单:

public class Data
{
   public string name {get; set;}
   public int width {get; set;}
}

我想创建一个只返回name属性列表的方法。像这样:

public List<string> GetAllNames()
{ return MyDataList<name>.ToList(); }

所以,如果我有这个清单:

  1. name = Jon - width = 10
  2. name =杰克 - width = 25
  3. 我想要以下列表:

    1. name = Jon
    2. name =杰克
    3. 有可能吗?

3 个答案:

答案 0 :(得分:22)

使用LINQ:

public List<string> GetAllNames()
{
    return MyDataList.Select(i => i.name).ToList();
}

答案 1 :(得分:2)

如果您使用的是.NET 3.5(VS2008)或更高版本,请使用扩展方法:

public class Data { String Name; Int32 Width; }
public List<Data> MyData = new List<Data>();

public static IEnumerable<String> GetNames(this List<Data> data) {
    foreach(Data d in data) yield return d.Name;
}
// or use Linq to return a concrete List<String> implementation rather than IEnumerable.

答案 2 :(得分:2)

public List<string> GetAllNames()
{ 
    return myDataList.Select(item => item.name).ToList();
}