I have a list of this class:
public class Data
{
public string name {get; set;}
public int width {get; set;}
}
And I want to make a method that return a list of only the name property. Like this:
public List<string> GetAllNames()
{ return MyDataList<name>.ToList(); }
So, if I have this list:
name
= Jon - width
= 10name
= Jack - width
= 25I want the following list:
name
= Jonname
= JackIs it possible?
Use LINQ:
public List<string> GetAllNames()
{
return MyDataList.Select(i => i.name).ToList();
}
If you're using .NET 3.5 (VS2008) or later then use Extension methods:
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.
public List<string> GetAllNames()
{
return myDataList.Select(item => item.name).ToList();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With