CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2006
    Posts
    134

    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

  2. #2
    Join Date
    Jan 2010
    Posts
    1,133

    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.

  3. #3
    Join Date
    Aug 2006
    Posts
    134

    Thumbs up 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
  •  





Click Here to Expand Forum to Full Width

Featured