Reputation: 2342
Is there a way to extract the Color type as a list from this List?
public List<object1> Color1 = new List<object1>()
{ new object1{Color=(Color)new ColorConverter().ConvertFrom("#FF016864"), Offset=0, Name="Color1"},
new object1{Color=(Color)new ColorConverter().ConvertFrom("#FF01706B"), Offset=20, Name="Color2"},
new object1{Color=(Color)new ColorConverter().ConvertFrom("#FF017873"), Offset=40, Name="Color3"},
new object1{Color=(Color)new ColorConverter().ConvertFrom("#FF018781"), Offset=60, Name="Color4"},
new object1{Color=(Color)new ColorConverter().ConvertFrom("#FF31A7A3"), Offset=80, Name="Color5"}
};
i.e. I want this:
public List<string> ColorNames ...
I need the string member of my Color1 List, how can I do this?
Upvotes: 0
Views: 217
Reputation: 11277
try using a select:
public List<string> ColorNames = Color1.Select(c => c.Name).ToList();
Upvotes: 0
Reputation: 1499800
LINQ is your friend:
List<string> names = Color1.Select(x => x.Name).ToList();
Or using List<T>.ConvertAll
:
List<string> names = Color1.ConvertAll(x => x.Name);
Personally I prefer using LINQ as it then works for non-lists as well, but ConvertAll
is very slightly more efficient as it knows the size of the destination list from the start.
It's worth learning more about LINQ - it's a fabulously useful set of technologies for data transformations. See the MSDN introduction page as a good starting point.
Upvotes: 7
Reputation: 292355
List<string> ColorNames = Color1.Select(c => c.Name).ToList();
Upvotes: 0
Reputation: 2524
var result = Color1.Select(x => x.Name).ToList()
Did you mean this list of strings?
Upvotes: 0