Reputation: 21999
I have a list with multiple variables and would like to add to an array the write to a text file.
class DataFields
{
public string name{get;set;}
public int id{get;set;}
public int age{get;set;}
}
List<DataFields> dfList;
would look something like
Adam 1234 23
Pete 3841 15
Scot 8435 30
DataFields[] result = dfList.ToArray();
File.WriteAllLines(@"C:\File\TextFile.txt", result);
I would like the result to be displayed in the text file similar to the list above but I am having trouble adding the list to the array then display in that order. Any ideas?
Upvotes: 1
Views: 524
Reputation: 6461
you could do something like this too..
List<DataFields> dfList = new List<DataFields>();
// populate dfList here
StreamWriter sw = new StreamWriter(@"C:\File\TextFile.txt");
foreach (DataFields df in dfList)
{
sw.WriteLine(df.id+"\t"+df.name+"\t"+df.age);
}
sw.Close();
or simply use foreach of List which is more efficient.
dfList.ForEach(df=> sw.WriteLine(df.id + "\t" + df.name + "\t" + df.age));
Upvotes: 0
Reputation: 15881
var result = dfList.Select(df => String.Format("{0}\t{1}\t{2}", df.name, df.id, df.age);
Upvotes: 3
Reputation: 34349
File.WriteAllLines
wants a collection of strings. You can generate one using LINQ:
List<DataFields> dfList = new List<DataFields>();
// populate dfList here
var formattedData =
dfList
.OrderBy(df => df.Name)
.Select(df => string.Format("{0} {1} {2}", df.Name, df.Id, df.Age));
File.WriteAllLines(@"C:\File\TextFile.txt", formattedData);
You should use PascalCase for your property names (Name, Id, Age).
Upvotes: 8