zoukankan      html  css  js  c++  java
  • 生成Csv格式的字符串

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    
    namespace Comon
    {
        public class CsvUtil
        {
            /// <summary>
            ///     生成Csv格式的字符串
            /// </summary>
            /// <typeparam name="T">数据源类型</typeparam>
            /// <param name="sourceDate">数据源</param>
            /// <param name="generateFileldDict">需要生成到Csv格式字段及描述</param>
            /// <returns></returns>
            public static string GenerateCsvFormate<T>(IList<T> sourceDate, IDictionary<string, string> generateFileldDict)
                where T : class, new()
            {
                if (sourceDate == null)
                {
                    throw new ArgumentNullException(nameof(sourceDate));
                }
    
                Type type = typeof(T);
                PropertyInfo[] propertyInfos = type.GetProperties();
    
                IList<string> fieldValueList = new List<string>(generateFileldDict.Count);
    
                StringBuilder builder = new StringBuilder();
    
                foreach (var filedName in generateFileldDict.Values)
                {
                    fieldValueList.Add(filedName);
                }
                builder.AppendLine(string.Join(",", fieldValueList));
    
                foreach (var item in sourceDate)
                {
                    fieldValueList.Clear();
                    foreach (var field in generateFileldDict.Keys)
                    {
                        PropertyInfo property = propertyInfos.FirstOrDefault(c => c.Name == field);
                        if (property != null)
                        {
                            var fieldValue = property.GetValue(item).ToString();
                            fieldValueList.Add(fieldValue);
                        }
                    }
                    builder.AppendLine(string.Join(",", fieldValueList));
                }
                return builder.ToString();
            }
        }
    }
    

      

  • 相关阅读:
    bzoj1045: [HAOI2008] 糖果传递(数论)
    bzoj1083: [SCOI2005]繁忙的都市(最小生成树)
    bzoj1079: [SCOI2008]着色方案(DP)
    BZOJ2467 [中山市选2010]生成树
    BZOJ4766 文艺计算姬
    BZOJ4894 天赋
    BZOJ2560 串珠子
    [SDOI2014]重建
    BZOJ3622 已经没有什么好害怕的了
    [SDOI2016]储能表
  • 原文地址:https://www.cnblogs.com/tangchun/p/10482632.html
Copyright © 2011-2022 走看看