I have a list and I get errors when trying to write the contents of the list into a text file. Why and how to fix it? (C #)


I have a list whose contents show up just fine in my dataGrid with this code:

dataGridView1.DataSource = lstExample;

This tells me my List is fine, and when I view the dataGrid it has all the data I need. But when I try to output the same List to a text file with this code:

string output = @"C:\output.txt";
File.WriteAllLines(output, lstExample);

I get this error:

Argument 2: cannot convert from 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<string>'

What do I need to do to fix this?

A simple example that shows what you have to do with your list:

List<int> lst = new List<int>();
File.WriteAllLines(@"C:\1\text.txt", lst.Select( i => i.ToString()));

simply you have to cast your anonymous type to string some how (maybe it would be string.Format("{0} {1}", i.A, i.B);