-
October 10th, 2012, 01:53 PM
#1
Lambda expression to get a list of members from a list of objects?
I don't even know how to come up with a good title for this question.
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?
Thanks very much!
RobR
-
October 11th, 2012, 02:20 PM
#2
Re: Lambda expression to get a list of members from a list of objects?
What you want to do is project MyObject instances into specific strings.
This is what the select keyword / extension method is for.
In method syntax:
Code:
var result = myObjectList.Select(element => element.myString); // this is applied to each element; element identifier is implicitly typed as MyObject
The => part is a lambda expression; => is read as "goes to", and the whole expression is actually an anonymous method, which you can basically understand as:
parameter => method_body
or
string AnonymousMethod(MyObject element) { return element.myString; }
This anonymous method is then called for each element in the collection, from within the Select() method, which uses the returned values to form a new collection.
Alternatively, you can use query syntax:
Code:
var result =
from elem in myObjectList
select elem.myString;
At the end, if necessary, you can call:
List<string> values = result.ToList();
Last edited by TheGreatCthulhu; October 11th, 2012 at 02:26 PM.
-
October 11th, 2012, 02:38 PM
#3
Re: Lambda expression to get a list of members from a list of objects?
Many thanks for your clear answer!
RobR
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|