Is there a quick way to convert an entity to .csv file?

前端 未结 3 1352
一生所求
一生所求 2021-02-03 12:28

at present, I have:

        string outputRow = string.Empty;
        foreach (var entityObject in entityObjects)
        {
            outputRow = entityObject.f         


        
3条回答
  •  借酒劲吻你
    2021-02-03 12:45

    string csv = "";
    //get property names from the first object using reflection    
    IEnumerable props = entityObjects.First().GetType().GetProperties();
    
    //header 
    csv += String.Join(", ",props.Select(prop => prop.Name)) + "\r\n";
    
    //rows
    foreach(var entityObject in entityObjects) 
    { 
        csv += String.Join(", ", props.Select(
            prop => ( prop.GetValue(entityObject, null) ?? "" ).ToString() 
        ) )
        + "\r\n";
    }
    
    • Would be better to use StringBuilder for lots of entitys
    • The code doesn't check for when entityObjects is empty

提交回复
热议问题