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?
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.
See more on this question at Stackoverflow