Home > Blockchain >  How to convert List<string> to List<object> specific property in C#
How to convert List<string> to List<object> specific property in C#

Time:11-09

How to convert List<string> to List<object> property in c#

We have a list of email id's

List<string> str= new List<string>{"[email protected]","[email protected]"};

and now we have to assign these email IDs to the list of an employee List<Employee> emailId property.

var emplist = new List<Employee>() ;

CodePudding user response:

You can use Select().

var emplist = str.Select(x => new Employee { EmailId = x}).ToList();

Select() is used for projecting each element of a sequence(in your case it is string email id) into a new sequence i.e. the Employee object.

CodePudding user response:

We can convert or assign List<string> to List<object> to specific property

//here Employee is an Object type
public static void Main(string[] args)
        {
            List<string> list = new List<string>() { "[email protected]", "[email protected]" }  ;
            var emplist= new List<Employee>() ;
            if(list.Any())
                list.ForEach(str => emplist.Add(new Employee { EmailId = str }));
            Console.ReadLine();
        }
        public class Employee {
            public string EmailId { get; set; }
            public string Address { get; set; }
        }
  • Related