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

前端 未结 3 1354
一生所求
一生所求 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:44

    I took Leniel's suggestion and wrapped it up in a full featured "writer" that also allows you to filter the properties you want written. Here's the code for your usage:

    public class CsvFileWriter
    {
        public static void WriteToFile(string filePath, List objs, string[] propertyNames)
        {
            var builder = new StringBuilder();
            var propertyInfos = RelevantPropertyInfos(propertyNames);
            foreach (var obj in objs)
                builder.AppendLine(CsvDataFor(obj, propertyInfos));
    
            File.WriteAllText(filePath, builder.ToString());
        }
    
        public static void WriteToFileSingleFieldOneLine(string filePath, List objs, string propertyName)
        {
            var builder = new StringBuilder();
            var propertyInfos = RelevantPropertyInfos(new[] { propertyName });
            for (var i = 0; i < objs.Count; i++)
            {
                builder.Append(CsvDataFor(objs[i], propertyInfos));
    
                if (i < objs.Count - 1)
                    builder.Append(",");
            }
    
            File.WriteAllText(filePath, builder.ToString());
        }
    
        private static List RelevantPropertyInfos(IEnumerable propertyNames)
        {
            var propertyInfos = typeof(T).GetProperties().Where(p => propertyNames.Contains(p.Name)).ToDictionary(pi => pi.Name, pi => pi);
            return (from propertyName in propertyNames where propertyInfos.ContainsKey(propertyName) select propertyInfos[propertyName]).ToList();
        }
    
        private static string CsvDataFor(object obj, IList propertyInfos)
        {
            if (obj == null)
                return "";
    
            var builder = new StringBuilder();
    
            for (var i = 0; i < propertyInfos.Count; i++)
            {
                builder.Append(propertyInfos[i].GetValue(obj, null));
    
                if (i < propertyInfos.Count - 1)
                    builder.Append(",");
            }
    
            return builder.ToString();
        }
    }
    

提交回复
热议问题