locked
Assign an Array of Values to a specific property in a List by using LINQ RRS feed

  • Question

  • Suppose I have a List<Product> which is empty and a List<String> with product names, ProductNames.  The Product class is:

    class Product { int id {get;set;} string Name {get; set;}

    }


    I want to assign all the ProductNames to the name field in the List<Product> by using LINQ Select. Currently I use

    List<string> names = GetProductNames();
    
    List<Product> products = new List<Product>();
    
    foreach (var item in names)
    {
       products.Add(new Product() { Name = item.ToString()});
    }
    But I would like to get rid of the foreach to have the code more clear. Thanks!

    Tuesday, April 1, 2014 3:45 PM

Answers

  • Hi. Here is the equivalent using select.

    List<Product> products = names.Select(n => new Product() { Name = n }).ToList();

    • Proposed as answer by amin, adnanMVP Tuesday, April 1, 2014 5:16 PM
    • Marked as answer by Trinakriae Wednesday, April 2, 2014 11:42 AM
    Tuesday, April 1, 2014 4:06 PM

All replies

  • Hi. Here is the equivalent using select.

    List<Product> products = names.Select(n => new Product() { Name = n }).ToList();

    • Proposed as answer by amin, adnanMVP Tuesday, April 1, 2014 5:16 PM
    • Marked as answer by Trinakriae Wednesday, April 2, 2014 11:42 AM
    Tuesday, April 1, 2014 4:06 PM
  • Thanks you very much, simple solution, I nfeel very dumb right now :-)
    Wednesday, April 2, 2014 11:42 AM