Search code examples
c#entity-frameworklinqstreamwriter

Data has strange format after saved to csv


My data after saved to csv has a format as show in the screenshot:

enter image description here

Here is my C# code.

UserDataDBsDataContext dataContext = new UserDataDBsDataContext();
            List<UserData> usersL = (from u in dataContext.UserDatas
                                         //where u.Id.Equals(13)
                                     select u).ToList();

 StreamWriter writer = new StreamWriter("my_data.txt");
 string csv = String.Join(",", usersL.Select(x => x.ToString()).ToArray());            
 writer.Write(csv);

 writer.Close();

Do you know what is missing or what I made wrong?

UPDATE: UserData.Properties:

enter image description here

Here I'm able to select property by property:

foreach (var i in usersL)
{
    writer.Write(i.Id);               
}

but I want to take whole object, as later then it will be uploaded to my app.


Solution

  • Try using something like this:

    Type t = typeof(UserData);
    PropertyInfo[] propInfos = t.GetProperties(BindingFlags.Public|BindingFlags.Instance);
    
    
    using(StreamWriter writer = new StreamWriter("my_data.txt"))
    {
    
        foreach(var user in usersL)
        {
    
            List<object> propValues = new List<object>();
            foreach(var pi in propInfos)
            {
                propValues.Add(pi.GetValue(user, null));
            }
    
            string csvLine = String.Join(",", propValues); 
    
            writer.WriteLine(csvLine);
        }
    }