CesarGon CesarGon - 1 year ago 67
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

List<Person> persons;

Now I would like to write a function to construct a sequence based on
, and having as elements the alternate values of
. 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 Source

Try this

persons.SelectMany(p => new[] { p.Name, p.Job });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download