开发者

Write C# Lists of objects in CSV file [closed]

It's difficult to tell what is being asked here. This question is ambiguous开发者_开发百科, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I have a C# object having 8 array elements of size 200.I need to print these arrays into a CSV file on respective labels. Data might contain string,int and double.

Ex:

time   time1   time2  Day  time4  time4 time5 time6 time7
1       5       9     Mon   7.0    8      9    5     NA
2
3
3
.
.
200    200    200    Sun   200    200   200   200    200

Oops, time1 etc are labels(Header) the data(8 lists having 200 elements) should write under these labels. Appreciate your response !


You could write a generic function to write the objects:

public void WriteCSV<T>(IEnumerable<T> items, string path)
{
  Type itemType = typeof(T);
  var props = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                      .OrderBy(p => p.Name);

  using (var writer = new StreamWriter(path))
  {
    writer.WriteLine(string.Join(", ", props.Select(p => p.Name)));

    foreach (var item in items)
    {
      writer.WriteLine(string.Join(", ", props.Select(p => p.GetValue(item, null))));
    }
  }
}

Used as:

var people = new List<Person> { new Person("Matt", "Abbott"), new Person("John Smith") };
WriteCSV(people, @"C:\people.csv");

Which might output:

Forename, Surname
Matt", Abbott"
John", Smith"


Assuming none of your data needs to have comma escaping, this should give you a general idea:

string[][] myArray = // your data
string[] myHeaders = // your headers
File.WriteAllText("somefile.csv", 
        string.Join(Environment.NewLine, 
            new[]{myHeaders}.Concat(myArray)
            .Select(line => string.Join(",", line))));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜