CesarGon CesarGon - 1 month ago 5
C# Question

Construct a sequence having two alternate properties of a class as elements

I have a class like this:

class Person
{
string Name;
string Job;
}


And I have a list of
Person
:

List<Person> persons;


Now I would like to write a function to construct a sequence based on
persons
, and having as elements the alternate values of
Name
and
Job
. For example, if I had:

persons.Add(new Person("Alice", "Accountant"));
persons.Add(new Person("Bob", "Butler"));
persons.Add(new Person("Chris", "Cleaner"));


Then the result of my function would be a sequence of strings like this:

"Alice", "Accountant", "Bob", "Butler", "Chris", "Cleaner"


Of course, I can do this by using a loop, but I'd like to find a way to do it in a single LINQ line, if possible.

Answer

Try this

persons.SelectMany(p => new[] { p.Name, p.Job });