Search code examples
c#linqlinqtocsv

LinqToCsv - Writing single objects to the file


I am using the LinqToCsv library for creating a comma delimited file and ran into a problem. I read the article about it here: http://www.codeproject.com/Articles/25133/LINQ-to-CSV-library

In my case my class design is something like this:

class AddressIndo
{
   public string City { get; set;}
   public string Street {get;set;}
}

class PersonInfo
{
   public PersonInfo()
   {
       this.AddressList = new List<AddressInfo> ; 
   }
   public string Name{get;set;}
   public string Phone {get;set;}
   public List AddressList <AddressInfo>  {get; set;}
}

So PersonInfo class itself has a list of addresses for that person. So now I want to write that PersonInfo objects to the file and looks like Write method of this library only takes an IEnumerable, but for example if the person has three addresses I want it to also create three rows in the output file. (yes the common info will be duplicated for each row). But I couldn't figure out how to do that? Because Write method only took an IEnumerable.


Solution

  • Not super ideal but if you have a single object and need to make several rows each with the same info except addresses you could do something like this:

    void Main()
    {
        var csvList = new List<PersonInfoCSVModel>();
        var yourPersonObject; //already filled with the data you want
    
        yourPersonObject.AddressList.ForEach(address =>
        {
            csvList.Add(new PersonInfoCSVModel()
            {
                Name = yourPersonObject.Name,
                Phone = yourPersonObject.Phone,
                City = address.City,
                Street = address.Street
            });
        });
    
        yourCSVContext.Write(csvList, "yourFile.csv");
    }
    
    class PersonInfoCSVModel
    {
        [CsvColumn(Name = "Name", FieldIndex = 1)]  
        public string Name{get;set;}
    
        [CsvColumn(Name = "Phone", FieldIndex = 2)] 
        public string Phone {get;set;}
    
        [CsvColumn(Name = "City", FieldIndex = 3)]  
        public string City { get; set;}
    
        [CsvColumn(Name = "Street", FieldIndex = 2)]    
        public string Street {get;set;}
    }