0

I have a list of Person objects

class Person
{
    string FirstName{get;set;}
    int Age {get;set;}
}

Now in this Person objects list

Person1 has FirstName="Alan", Age=20

Person 2 has FirstName="Josephine", Age=21

I need to get a new List, where each list item has the first name concatenated with the age

List I need:

Alan:20

Josephine:21

...so on

I have this so far...

var PersonConcatenatedList= from p in PersonList
                            select new {firstName= p.FirstName, Age=p.Age};

err...but now how to ouput the desired list format ? :(

Any help will be greatly appreciated. thanks

2 Answers 2

3

Use string.Join:

var PersonConcatenatedList = PersonList
                            .Select(x => string.Join(":", x.FirstName, x.Age));

Since you need a list of strings you shouldn't create ananymous types.Simple string concatanation would also work:

PersonList.Select(x => x.FirstName + ":" + x.Age));

If you want output as a single string, then use string.Join via Environment.NewLine and concatanate the results with new line character:

var output = string.Join(Environment.NewLine, PersonConcatenatedList);
Sign up to request clarification or add additional context in comments.

1 Comment

The result will be a collection, so you can format the new line after each iteration in the UI.
1

String.Join() is one way to go. But for good programming I suggest implementing the .ToString() method.

class Person
{
    string FirstName { get; set; }
    int Age { get; set; }

    public override string ToString()
    {
        return this.FirstName + ":" + this.Age;
    }
}

Then simply use the following:

var result = personList.Select(person => person.ToString());

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.