locked
convert foreach to Linq RRS feed

  • Question

  • I wished to convert the below foreach to a single statement using Linq

     

     class Test
        {
            public string Name;
            public Test(string s)
            {
                Name = s;
            }
        }

     

    static IList<Test> Items = new List<Test>(); static void Main(string[] args) { Items.Add(new Test("AB")); Items.Add(new Test("bc")); Items.Add(new Test("CD")); IList<string> list = new List<string>(); foreach (Test s in Items) { list.Add(s.Name); } }


    Sunday, August 25, 2013 10:45 PM

Answers

  • Hi PARTITION;

    To do what you want remove the following line of code

    IList<string> list = new List<string>();

    And then add this line of code

    IList<string> list = Items.Select( n => n.Name ).ToList();

    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Monday, August 26, 2013 1:38 AM

All replies

  • Hi PARTITION;

    To do what you want remove the following line of code

    IList<string> list = new List<string>();

    And then add this line of code

    IList<string> list = Items.Select( n => n.Name ).ToList();

    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Monday, August 26, 2013 1:38 AM
  •   

    Did this answered your question? 

      


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Thursday, August 29, 2013 2:28 AM