Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create List with only one class member

Tags:

c#

list

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:

  1. name = Jon - width = 10
  2. name = Jack - width = 25

I want the following list:

  1. name = Jon
  2. name = Jack

Is it possible?

like image 494
Nick Avatar asked Jun 22 '12 13:06

Nick


3 Answers

Use LINQ:

public List<string> GetAllNames()
{
    return MyDataList.Select(i => i.name).ToList();
}
like image 178
StriplingWarrior Avatar answered Nov 14 '22 10:11

StriplingWarrior


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.
like image 20
Dai Avatar answered Nov 14 '22 10:11

Dai


public List<string> GetAllNames()
{ 
    return myDataList.Select(item => item.name).ToList();
}
like image 2
Dave New Avatar answered Nov 14 '22 10:11

Dave New