0

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 }));
4
  • 2
    strArr.Split(',').Select(x => new Employee() {...}).ToList()? Commented Oct 19, 2021 at 7:04
  • wow!! great!! This was really helpful. Commented Oct 19, 2021 at 7:30
  • @canton7 if you post it as an answer, I will accept it, otherwise I will accept 4lexKislitsyn's answer. You were first and I would like to give the honor to you first. Commented Oct 20, 2021 at 17:38
  • @4lex's answer is perfectly good: accept that Commented Oct 20, 2021 at 17:46

1 Answer 1

1

as @canton7 said in comments you can use Linq:

strArr?.Split(',').Select(x => new Employee() {...}).ToList() ?? new List<Employee>()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.