1

I am using VS 2008.

I have a little user control that has a method whose argument is of type List<String>. I have a list of objects (call it MyObjectList, of type List<MyObject>) whose definition includes one String member (call it myString).

I want to get a List<String> that contains all of the myString strings from MyObjectList.

Of course, I can write a little loop that walks through MyObjectList, adding every myString value to a List<String> object. But I am trying to be as modern as I can.

With the advent of lambda expressions, I think there must be a better way to do this. Is there? If so, how? And is the answer any different in VS 2012?

1 Answer 1

4

Assuming that your list is a List<MyObject> and that class MyObject has a property MyString, you could use LINQ and a lambda to do this:

var listOfStrings = myObjectList.Select(o => o.MyString).ToList();

This will work in any assembly that targets .NET 3.0 or greater; the version of VS doesn't matter.

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

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.