Bertrand Paul Bertrand Paul - 16 days ago 7
C# Question

Convert a generic collection to a List of strings

After searching the board, i was not able to find a solution to my problem.

I have written the following code that works pretty well:

public static void CreateFile(this List<string> lines,File_attribute fa)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(fa.OutpoutFolder+ fa.FileName ))
{
foreach (string line in lines)
{

file.WriteLine(line);

}
}
}


Now, i want to be able to do just this with a generic collection of object. I want each property to just be "ToStringed". Here is the start of my code:

public static void CreateFile<T>(this List<T> lines, File_attribute fa)
{
List<string> mylist = new List<string>();
...............
...............


Any help will be highly appreciated.

Answer

Here's a possible alternate approach using string.Join:

public static void CreateFile<T>(this List<T> lines, File_attribute fa)
{
     File.WriteAllText
     (
          Path.Combine(fa.OutpoutFolder, fa.FileName),
          string.Join(Environment.NewLine, lines)
     );
}

So string.Join will internally call Object.ToString()!