Home > Net >  convert string in an array of objects
convert string in an array of objects

Time:10-21

I have two different classes: Employee and Customer. Each have two properties in common: Name and Address. Is there a way convert the string directly into an array of objects without using the List<>?

    private static List<Employee> NewMethod1(string strArr)
    {
        List<Employee> lst = new List<Employee>();
        if (strArr !=null)
        {
            strArr.Split(',').ToList().ForEach(x => lst.Add(new Employee() { Name = x }));
        }
        return lst.ToArray();
    }

or make this line of code generic enough so I can use it inline code?

strArr.Split(',').ToList().ForEach(x => lst.Add(new Employee() { Name = x }));

CodePudding user response:

as @canton7 said in comments you can use Linq:

strArr?.Split(',').Select(x => new Employee() {...}).ToList() ?? new List<Employee>()
  • Related