Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a tab delimited string from a list of object

Tags:

c#

linq

I have a list of objects call Person I would like to create a tab delimited string from the list

Example:

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



List<Person> persons = new List<Persons>();

persons.add ( new person {"bob",15,"999-999-0000"} )
persons.add ( new person {"sue",25,"999-999-0000"} )
persons.add ( new person {"larry",75,"999-999-0000"} )

I would like to output that list to a string that would look like this:

"bob\t15\t999-999-0000\r\nsue\t25\999-999-0000\r\nlarry\t75\999-999-0000\r\n"

right now I was just going to loop through the list and do it line by line the old fashion way.. I was wondering if the was a short cut in LINQ.

like image 677
Arcadian Avatar asked Dec 27 '22 11:12

Arcadian


1 Answers

Aggregate formatted person strings with StringBuilder. Thus you will avoid creating lot of strings in memory:

var result = persons.Aggregate(
    new StringBuilder(),
    (sb, p) => sb.AppendFormat("{0}\t{1}\t{2}\r\n", p.FirstName, p.Age, p.Phone),
    sb => sb.ToString());
like image 140
Sergey Berezovskiy Avatar answered Jan 15 '23 19:01

Sergey Berezovskiy