Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a line of code that prints a list to console for me which works fine.

LinkRecords.ForEach(record => Console.WriteLine({record.academic.Name}));


Now I am trying to write the contents to a file, I created a ToString object called

public override string ToString(){return($"{this.academicName}");}

and my line of code is

File.AppendAllLines(@"C:\pg\Gold\BRdata.txt",LinkRecords.ToString());

My error message is on the LinkRecords.ToString() saying that I can not convert from 'string' to 'System.Collections.Generic.IEnumerable,<string>'

Appreciate any assistance with this please.
Posted

There's no need to abuse string interpolation for your ToString method - just return the property directly:
C#
public override string ToString()
{
    return this.academic.Name;
}

The File.AppendAllLines method expects the second parameter to be an IEnumerable<string>, but you are passing in a string instead. You need to pass in a list containing the string representation of each item. LINQ makes this particularly easy:
C#
File.AppendAllLines(@"C:\pg\Gold\BRdata.txt", LinkRecords.Select(r => r.ToString()));

// Or:
File.AppendAllLines(@"C:\pg\Gold\BRdata.txt", LinkRecords.Select(r => r.academic.Name));
 
Share this answer
 
Comments
Member 12009796 25-Nov-15 13:38pm    
Okay that makes perfect sense.
When you are passing LinkRecords to ToString() method, its taken as LinkRecords.academicName which is wrong because you are not iterating through LinkRecords.

Instead overriding ToString() method, I would do it this way.
C#
private string GetAcademicNames(LinkRecords linkRecords)
{
    StringBuilder sb = new StringBuilder();
    linkRecords.ForEach(record => sb.Append(record.academic.Name));

    return sb.ToString();

}

File.AppendAllLines(@"C:\pg\Gold\BRdata.txt",GetAcademicNames(linkRecords));
 
Share this answer
 
Comments
Richard Deeming 25-Nov-15 13:28pm    
File.AppendAllLines expects the second parameter to be IEnumerable<string>, but you're passing in a single string instead. You'd need to use File.AppendAllText instead.

You'd also need to replace sb.Append with sb.AppendLine to get a line break between each item.
RaisKazi 25-Nov-15 14:57pm    
Thanks, its good to learn and u got my 5+.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900