简体   繁体   中英

How do I print the contents of my list into a text file?

I have restaurant data and I am trying to analyze who visited a particular Restaurant X. The data has this structure:

public class RestaurantXPatrons
{
    public String PatronName { get; set;}
    public List <strings> DateofVisits = new List <strings>();
}

I created a List of RestaurantXPatrons called lstX, and I want to output lstX to a tab-delimited text file (for viewing in Excel at a later time). So here's my output code:

var output = lstX.Select ( x => x.PatronName + "\t" + x.DateofVisits );
string filepath = @"C:\data.txt";
System.IO.File.WriteAllLines(filepath, output);

When I view the results in Excel or Notepad, I see "System.Collections.Generic.List`1[System.String] " where there should be the contents of the DateofVisits list for each Patron of Restaurant X. My question is, how do I get the contents of the list into my output?

You need to either do something like x.DateOfVisits.FirstOrDefault() (to get the first instance) or flatten the list to string like: String.Join("; ", x.DateOfVisits) .

Alternatively if you want to do something like:

Paul    01/01/2013
Paul    01/02/2013
Sally   01/01/2013

You could do

from x in listX
group x by new { x.PatronName, x.DateOfVisit } into g
select new String(g.Key.PatronName + "\t" + g.Key.DateOfVisit)

...don't have anything I can test with so this is all done "blind" as it were - hopefully will get you on right track.

you need to iterate through the collection (output variable) and then write them into a StringBuilder perhaps or write them directly to disk by using WriteLine on the StreamWriter object.

when you hover over the var variable, you will see it is a type of a collection being returned by the Select method (LINQ extension method). you need to iterate through it and write it line by line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM