0

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?

2
  • 3
    Consider renaming your object1 class. Commented Nov 25, 2013 at 13:27
  • @JeppeStigNielsen I renamed my original class to object1 just for the question Commented Nov 25, 2013 at 13:29

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

0
var result = Color1.Select(x => x.Name).ToList()

Did you mean this list of strings?

Comments

0
List<string> ColorNames = Color1.Select(c => c.Name).ToList();

Comments

0

try using a select:

public List<string> ColorNames = Color1.Select(c => c.Name).ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.