我有这个班级的清单:
public class Data
{
public string name {get; set;}
public int width {get; set;}
}
我想创建一个只返回name属性列表的方法。像这样:
public List<string> GetAllNames()
{ return MyDataList<name>.ToList(); }
所以,如果我有这个清单:
name
= Jon - width
= 10 name
=杰克 - width
= 25 我想要以下列表:
name
= Jon name
=杰克有可能吗?
答案 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();
}