Create a tab delimited string from the list of objects

I have a list of objects calling Person. I would like to create a tab delimited string from a 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 print this list on a line 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 iterate over the list and do it one by one in the old way. I was wondering if there was a short snippet in LINQ.

+4
source share
3 answers

You can use Strig.Join

 string str = string.Join(Environment.NewLine, person.Select(r=> r.FirstName +@ "\t" + r.Age + @"\t" + r.Phone")) 
+4
source

A collection of character formatted strings with StringBuilder . This way you will avoid creating a large number of lines 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()); 
+5
source
 persons.ForEach(q => output+=(q.firstname+"\\"+q.Age.ToString()+"\\"+q.Phone+"\\")); 
0
source

All Articles