Exemplo n.º 1
0
        // Internal Field/Property helper
        //    public static TField GetTypeFieldValueAs<T, TField>(this T obj, string fieldName) => typeof(T).GetFieldValueAs<T, TField>(fieldName, obj);
        //    public static TProperty GetTypePropertyValueAs<T, TProperty>(this T obj, string propertyName) => typeof(T).GetPropertyValueAs<T, TProperty>(propertyName, obj);

        public static string ToCsv <T>(this IEnumerable <T> objectlist, List <string> excludedPropertyNames = null, bool quoteEveryField = false, bool includeFieldNamesAsFirstRow = true)
        {
            if (excludedPropertyNames == null)
            {
                excludedPropertyNames = new List <string>();
            }
            var separator    = ",";
            var t            = typeof(T);
            var props        = t.GetProperties();
            var arrPropNames = props.Where(p => !excludedPropertyNames.Contains(p.Name)).Select(f => f.Name).ToArray();
            var csvBuilder   = new StringBuilder();

            if (includeFieldNamesAsFirstRow)
            {
                if (quoteEveryField)
                {
                    for (var i = 0; i <= arrPropNames.Length - 1; i++)
                    {
                        if (i > 0)
                        {
                            csvBuilder.Append(separator);
                        }
                        csvBuilder.Append("\"");
                        csvBuilder.Append(arrPropNames[i]);
                        csvBuilder.Append("\"");
                    }
                    csvBuilder.Append(Environment.NewLine);
                }
                else
                {
                    var header = string.Join(separator, arrPropNames);
                    csvBuilder.AppendLine(header);
                }
            }
            foreach (var o in objectlist)
            {
                csvBuilder.AppendCsvRow(excludedPropertyNames, separator, quoteEveryField, props, o);
                csvBuilder.Append(Environment.NewLine);
            }
            return(csvBuilder.ToString());
        }