将通用列表转换为CSV字符串

时间:2009-12-11 18:45:54

标签: c# generics .net-3.5

我有一个整数值列表(List),并希望生成一个逗号分隔值的字符串。这就是列表输出中的所有项目都是单个逗号分隔列表。

我的想法...... 1.将列表传递给方法。 2.使用stringbuilder迭代列表并附加逗号 3.测试最后一个字符,如果是逗号,请将其删除。

你有什么想法?这是最好的方式吗?

如果我不仅要处理整数(我当前的计划),还要处理字符串,longs,double,bools等等,我的代码将会如何变化?我想让它接受任何类型的列表。

15 个答案:

答案 0 :(得分:219)

框架已经为我们做了很多事。

List<int> myValues;
string csv = String.Join(",", myValues.Select(x => x.ToString()).ToArray());

对于一般情况:

IEnumerable<T> myList;
string csv = String.Join(",", myList.Select(x => x.ToString()).ToArray());

正如你所看到的,它实际上并没有什么不同。请注意,如果x.ToString()包含逗号,您可能需要将"\"" + x.ToString() + "\""实际包含在引号中(即x.ToString())。

有关此略有变化的有趣读物:请参阅Eric Lippert博客上的Comma Quibbling

注意:这是在.NET 4.0正式发布之前编写的。现在我们可以说

IEnumerable<T> sequence;
string csv = String.Join(",", sequence);

使用重载String.Join<T>(string, IEnumerable<T>)。此方法会自动将每个元素x投影到x.ToString()

答案 1 :(得分:11)

在3.5中,我仍然能够做到这一点。它更简单,也不需要lambda。

String.Join(",", myList.ToArray<string>());

答案 2 :(得分:10)

您可以创建一个可以在任何IEnumerable上调用的扩展方法:

public static string JoinStrings<T>(
    this IEnumerable<T> values, string separator)
{
    var stringValues = values.Select(item =>
        (item == null ? string.Empty : item.ToString()));
    return string.Join(separator, stringValues.ToArray());
}

然后你可以在原始列表上调用该方法:

string commaSeparated = myList.JoinStrings(", ");

答案 3 :(得分:7)

您可以使用String.Join

String.Join(
  ",",
  Array.ConvertAll(
     list.ToArray(),
     element => element.ToString()
  )
);

答案 4 :(得分:6)

如果有任何人想要转换自定义类对象的列表而不是字符串列表,那么使用您的类的csv行表示覆盖您的类的ToString方法。< / p>

Public Class MyClass{
   public int Id{get;set;}
   public String PropertyA{get;set;}
   public override string ToString()
   {
     return this.Id+ "," + this.PropertyA;
   }
}

然后,可以使用以下代码将此类列表转换为CSV 标题列

string csvHeaderRow = String.Join(",", typeof(MyClass).GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(x => x.Name).ToArray<string>()) + Environment.NewLine;
string csv= csvHeaderRow + String.Join(Environment.NewLine, MyClass.Select(x => x.ToString()).ToArray());

答案 5 :(得分:5)

作为@Frank Create a CSV File from a .NET Generic List给出的链接中的代码,有一个问题是用,结束每一行我修改了代码以摆脱它。希望它可以帮助某人。< / p>

/// <summary>
/// Creates the CSV from a generic list.
/// </summary>;
/// <typeparam name="T"></typeparam>;
/// <param name="list">The list.</param>;
/// <param name="csvNameWithExt">Name of CSV (w/ path) w/ file ext.</param>;
public static void CreateCSVFromGenericList<T>(List<T> list, string csvCompletePath)
{
    if (list == null || list.Count == 0) return;

    //get type from 0th member
    Type t = list[0].GetType();
    string newLine = Environment.NewLine;

    if (!Directory.Exists(Path.GetDirectoryName(csvCompletePath))) Directory.CreateDirectory(Path.GetDirectoryName(csvCompletePath));

    if (!File.Exists(csvCompletePath)) File.Create(csvCompletePath);

    using (var sw = new StreamWriter(csvCompletePath))
    {
        //make a new instance of the class name we figured out to get its props
        object o = Activator.CreateInstance(t);
        //gets all properties
        PropertyInfo[] props = o.GetType().GetProperties();

        //foreach of the properties in class above, write out properties
        //this is the header row
        sw.Write(string.Join(",", props.Select(d => d.Name).ToArray()) + newLine);

        //this acts as datarow
        foreach (T item in list)
        {
            //this acts as datacolumn
            var row = string.Join(",", props.Select(d => item.GetType()
                                                            .GetProperty(d.Name)
                                                            .GetValue(item, null)
                                                            .ToString())
                                                    .ToArray());
            sw.Write(row + newLine);

        }
    }
}

答案 6 :(得分:3)

任何解决方案仅在列出列表(字符串)

时才有效

如果您拥有自己的对象的通用列表,例如汽车具有n个属性的列表(汽车),则必须循环每个汽车对象的PropertiesInfo。

请注意:http://www.csharptocsharp.com/generate-csv-from-generic-list

答案 7 :(得分:3)

我喜欢一个很好的简单扩展方法

 public static string ToCsv(this List<string> itemList)
         {
             return string.Join(",", itemList);
         }

然后你可以在原始列表上调用该方法:

string CsvString = myList.ToCsv();

比其他一些建议更清洁,更容易阅读。

答案 8 :(得分:3)

我在这个post中深入解释。我只需在此处粘贴代码并附上简要说明。

这是创建标题行的方法。它使用属性名称作为列名。

private static void CreateHeader<T>(List<T> list, StreamWriter sw)
    {
        PropertyInfo[] properties = typeof(T).GetProperties();
        for (int i = 0; i < properties.Length - 1; i++)
        {
            sw.Write(properties[i].Name + ",");
        }
        var lastProp = properties[properties.Length - 1].Name;
        sw.Write(lastProp + sw.NewLine);
    }

此方法创建所有值行

private static void CreateRows<T>(List<T> list, StreamWriter sw)
    {
        foreach (var item in list)
        {
            PropertyInfo[] properties = typeof(T).GetProperties();
            for (int i = 0; i < properties.Length - 1; i++)
            {
                var prop = properties[i];
                sw.Write(prop.GetValue(item) + ",");
            }
            var lastProp = properties[properties.Length - 1];
            sw.Write(lastProp.GetValue(item) + sw.NewLine);
        }
    }

以下是将它们组合在一起并创建实际文件的方法。

public static void CreateCSV<T>(List<T> list, string filePath)
    {
        using (StreamWriter sw = new StreamWriter(filePath))
        {
            CreateHeader(list, sw);
            CreateRows(list, sw);
        }
    }

答案 9 :(得分:2)

CsvHelper库在Nuget非常受欢迎。你值得拥有,伙计! https://github.com/JoshClose/CsvHelper/wiki/Basics

使用CsvHelper非常简单。它的默认设置是针对最常见的场景设置的。

这是一个小设置数据。

Actors.csv:

Id,FirstName,LastName  
1,Arnold,Schwarzenegger  
2,Matt,Damon  
3,Christian,Bale

Actor.cs(代表演员的自定义类对象):

public class Actor
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

使用CsvReader读取CSV文件:

var csv = new CsvReader( new StreamReader( "Actors.csv" ) );

var actorsList = csv.GetRecords();

写入CSV文件。

using (var csv = new CsvWriter( new StreamWriter( "Actors.csv" ) )) 
{
    csv.WriteRecords( actorsList );
}

答案 10 :(得分:1)

无论出于何种原因,@ AliUmair都将编辑还原为他的答案,从而修复了无法按原样运行的代码,因此,这里是没有文件访问错误并且可以正确处理空对象属性值的工作版本:

public static string GetJsonPropertyName(Type type, string propertyName)
{
    if (type is null)
        throw new ArgumentNullException(nameof(type));

    return type.GetProperty(propertyName)
        ?.GetCustomAttribute<JsonPropertyAttribute>()
        ?.PropertyName;
}

答案 11 :(得分:1)

这是我的扩展方法,为简单起见,它返回一个字符串,但我的实现将文件写入数据湖。

它提供任何定界符,在字符串中添加引号(如果它们包含定界符),并且交易将为空和空白。

    /// <summary>
    /// A class to hold extension methods for C# Lists 
    /// </summary>
    public static class ListExtensions
    {
        /// <summary>
        /// Convert a list of Type T to a CSV
        /// </summary>
        /// <typeparam name="T">The type of the object held in the list</typeparam>
        /// <param name="items">The list of items to process</param>
        /// <param name="delimiter">Specify the delimiter, default is ,</param>
        /// <returns></returns>
        public static string ToCsv<T>(this List<T> items, string delimiter = ",")
        {
            Type itemType = typeof(T);
            var props = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance).OrderBy(p => p.Name);

            var csv = new StringBuilder();

            // Write Headers
            csv.AppendLine(string.Join(delimiter, props.Select(p => p.Name)));

            // Write Rows
            foreach (var item in items)
            {
                // Write Fields
                csv.AppendLine(string.Join(delimiter, props.Select(p => GetCsvFieldasedOnValue(p, item))));
            }

            return csv.ToString();
        }

        /// <summary>
        /// Provide generic and specific handling of fields
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="p"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        private static object GetCsvFieldasedOnValue<T>(PropertyInfo p, T item)
        {
            string value = "";

            try
            {
                value = p.GetValue(item, null)?.ToString();
                if (value == null) return "NULL";  // Deal with nulls
                if (value.Trim().Length == 0) return ""; // Deal with spaces and blanks

                // Guard strings with "s, they may contain the delimiter!
                if (p.PropertyType == typeof(string))
                {
                    value = string.Format("\"{0}\"", value);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return value;
        }
    }

用法:

 // Tab Delimited (TSV)
 var csv = MyList.ToCsv<MyClass>("\t");

答案 12 :(得分:0)

http://cc.davelozinski.com/c-sharp/the-fastest-way-to-read-and-process-text-files

这个网站做了一些关于如何使用缓冲写入器写入文件的广泛测试,逐行读取似乎是最好的方法,使用字符串构建器是最慢的之一。

我使用他的技术大量写东西来存档效果很好。

答案 13 :(得分:0)

String.Join的问题在于您没有处理值中已存在逗号的情况。当逗号存在时,您将在引号中包围该值,并用双引号替换所有现有的引号。

String.Join(",",{"this value has a , in it","This one doesn't", "This one , does"});

请参阅CSV Module

答案 14 :(得分:0)

通用ToCsv()扩展方法:

  • 支持Int16 / 32/64,float,double,decimal和任何支持 的ToString()
  • 可选的自定义联接分隔符
  • 可选的自定义选择器
  • 可选的空/空处理规范(* Opt()重载)

用法示例:

"123".ToCsv() // "1,2,3"
"123".ToCsv(", ") // "1, 2, 3"
new List<int> { 1, 2, 3 }.ToCsv() // "1,2,3"

new List<Tuple<int, string>> 
{ 
    Tuple.Create(1, "One"), 
    Tuple.Create(2, "Two") 
}
.ToCsv(t => t.Item2);  // "One,Two"

((string)null).ToCsv() // throws exception
((string)null).ToCsvOpt() // ""
((string)null).ToCsvOpt(ReturnNullCsv.WhenNull) // null

实施

/// <summary>
/// Specifies when ToCsv() should return null.  Refer to ToCsv() for IEnumerable[T]
/// </summary>
public enum ReturnNullCsv
{
    /// <summary>
    /// Return String.Empty when the input list is null or empty.
    /// </summary>
    Never,

    /// <summary>
    /// Return null only if input list is null.  Return String.Empty if list is empty.
    /// </summary>
    WhenNull,

    /// <summary>
    /// Return null when the input list is null or empty
    /// </summary>
    WhenNullOrEmpty,

    /// <summary>
    /// Throw if the argument is null
    /// </summary>
    ThrowIfNull
}   

/// <summary>
/// Converts IEnumerable list of values to a comma separated string values.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="values">The values.</param>        
/// <param name="joinSeparator"></param>
/// <returns>System.String.</returns>
public static string ToCsv<T>(
    this IEnumerable<T> values,            
    string joinSeparator = ",")
{
    return ToCsvOpt<T>(values, null /*selector*/, ReturnNullCsv.ThrowIfNull, joinSeparator);
}

/// <summary>
/// Converts IEnumerable list of values to a comma separated string values.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="values">The values.</param>
/// <param name="selector">An optional selector</param>
/// <param name="joinSeparator"></param>
/// <returns>System.String.</returns>
public static string ToCsv<T>(
    this IEnumerable<T> values,
    Func<T, string> selector,            
    string joinSeparator = ",") 
{
    return ToCsvOpt<T>(values, selector, ReturnNullCsv.ThrowIfNull, joinSeparator);
}

/// <summary>
/// Converts IEnumerable list of values to a comma separated string values.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="values">The values.</param>
/// <param name="returnNullCsv">Return mode (refer to enum ReturnNullCsv).</param>
/// <param name="joinSeparator"></param>
/// <returns>System.String.</returns>
public static string ToCsvOpt<T>(
    this IEnumerable<T> values,
    ReturnNullCsv returnNullCsv = ReturnNullCsv.Never,
    string joinSeparator = ",")
{
    return ToCsvOpt<T>(values, null /*selector*/, returnNullCsv, joinSeparator);
}

/// <summary>
/// Converts IEnumerable list of values to a comma separated string values.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="values">The values.</param>
/// <param name="selector">An optional selector</param>
/// <param name="returnNullCsv">Return mode (refer to enum ReturnNullCsv).</param>
/// <param name="joinSeparator"></param>
/// <returns>System.String.</returns>
public static string ToCsvOpt<T>(
    this IEnumerable<T> values, 
    Func<T, string> selector,
    ReturnNullCsv returnNullCsv = ReturnNullCsv.Never,
    string joinSeparator = ",")
{
    switch (returnNullCsv)
    {
        case ReturnNullCsv.Never:
            if (!values.AnyOpt())
                return string.Empty;
            break;

        case ReturnNullCsv.WhenNull:
            if (values == null)
                return null;
            break;

        case ReturnNullCsv.WhenNullOrEmpty:
            if (!values.AnyOpt())
                return null;
            break;

        case ReturnNullCsv.ThrowIfNull:
            if (values == null)
                throw new ArgumentOutOfRangeException("ToCsvOpt was passed a null value with ReturnNullCsv = ThrowIfNull.");
            break;

        default:
            throw new ArgumentOutOfRangeException("returnNullCsv", returnNullCsv, "Out of range.");
    }

    if (selector == null)
    {
        if (typeof(T) == typeof(Int16) || 
            typeof(T) == typeof(Int32) || 
            typeof(T) == typeof(Int64))
        {                   
            selector = (v) => Convert.ToInt64(v).ToStringInvariant();
        }
        else if (typeof(T) == typeof(decimal))
        {
            selector = (v) => Convert.ToDecimal(v).ToStringInvariant();
        }
        else if (typeof(T) == typeof(float) ||
                typeof(T) == typeof(double))
        {
            selector = (v) => Convert.ToDouble(v).ToString(CultureInfo.InvariantCulture);
        }
        else
        {
            selector = (v) => v.ToString();
        }            
    }

    return String.Join(joinSeparator, values.Select(v => selector(v)));
}

public static string ToStringInvariantOpt(this Decimal? d)
{
    return d.HasValue ? d.Value.ToStringInvariant() : null;
}

public static string ToStringInvariant(this Decimal d)
{
    return d.ToString(CultureInfo.InvariantCulture);
}

public static string ToStringInvariantOpt(this Int64? l)
{
    return l.HasValue ? l.Value.ToStringInvariant() : null;
}

public static string ToStringInvariant(this Int64 l)
{
    return l.ToString(CultureInfo.InvariantCulture);
}

public static string ToStringInvariantOpt(this Int32? i)
{
    return i.HasValue ? i.Value.ToStringInvariant() : null;
}

public static string ToStringInvariant(this Int32 i)
{
    return i.ToString(CultureInfo.InvariantCulture);
}

public static string ToStringInvariantOpt(this Int16? i)
{
    return i.HasValue ? i.Value.ToStringInvariant() : null;
}

public static string ToStringInvariant(this Int16 i)
{
    return i.ToString(CultureInfo.InvariantCulture);
}
相关问题