Convert string array to custom object list using linq

16,297

I would use Linq's Select extension and ToList to convert the IEnumerable (from Select extension) to a list

An Example:

string[] randomArray = new string[3] {"1", "2", "3"};
List<CustomEntity> listOfEntities = randomArray.Select(item => new CustomEntity() { FileName = item } ).ToList();
Share:
16,297

Related videos on Youtube

Neeraj Kumar Gupta
Author by

Neeraj Kumar Gupta

Updated on June 19, 2022

Comments

  • Neeraj Kumar Gupta
    Neeraj Kumar Gupta almost 2 years

    I have a class with one public property.

    public class CustomEntity 
    {
        string _FileName;
        public string FileName
        {
            get { return _FileName; }
            set
            {                    
               _FileName = value;
    
            }
        }
    
    }
    

    I have array of string which I want to convert in List of "CustomEntity" using linq. please suggest me how I can do that.

    • Jon Skeet
      Jon Skeet about 11 years
      Well, how much research have you done? What's the purpose of your Instance property (which confusingly will return a new instance on each call)? Note that not having an accessible constructor will mean you can't use object initializers.
  • WinW
    WinW over 5 years
    wouldn't it be sufficient enough to use just: List<CustomEntity> = randomArray.ToList()

Related