C# 创建只有一个类成员的列表
我有这门课的名单:C# 创建只有一个类成员的列表,c#,list,C#,List,我有这门课的名单: public class Data { public string name {get; set;} public int width {get; set;} } 我想创建一个只返回name属性列表的方法。像这样: public List<string> GetAllNames() { return MyDataList<name>.ToList(); } public List GetAllNames() {返回MyDataList.
public class Data
{
public string name {get; set;}
public int width {get; set;}
}
我想创建一个只返回name属性列表的方法。像这样:
public List<string> GetAllNames()
{ return MyDataList<name>.ToList(); }
public List GetAllNames()
{返回MyDataList.ToList();}
因此,如果我有以下清单:
名称
=Jon-宽度
=10名称
=插孔-宽度
=25name
=Jon名称
=插孔public List<string> GetAllNames()
{
return MyDataList.Select(i => i.name).ToList();
}
public List GetAllNames()
{
返回MyDataList.Select(i=>i.name).ToList();
}
如果您使用的是.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.
公共类数据{String Name;Int32 Width;}
public List MyData=new List();
公共静态IEnumerable GetNames(此列表数据){
foreach(数据中的数据d)返回d.Name;
}
//或者使用Linq返回具体的列表实现,而不是IEnumerable。
公共列表GetAllNames()
{
返回myDataList.Select(item=>item.name).ToList();
}
请注意,如果您返回一个列表,那么您将基本上复制整个列表。如果您有一个大的列表,这可能需要时间/内存。如果您切换到使用IEnumerable,然后不执行.ToList(),那么您将得到一个几乎可以自由创建的惰性列表,并且消耗的数据量很少(<100字节)space@TimothyBaldridge:是的。还值得注意的是,如果您使用IEnumerable
路径,则每次迭代时都会重新计算它。您的IEnumerable还与原始对象集绑定,因此它将阻止垃圾收集器清理所有数据
对象,即使您只计划使用它们的名称。此外,如果MyDataList
发生更改,则返回的IEnumerable
将发生更改,如果在单独的线程中使用,则可能引发异常。通常这些都不重要,但了解在幕后发生的事情总是好的。
public List<string> GetAllNames()
{
return myDataList.Select(item => item.name).ToList();
}