Join collection of objects into comma-separated string

前端 未结 11 1352
无人共我
无人共我 2020-12-07 19:22

In many places in our code we have collections of objects, from which we need to create a comma-separated list. The type of collection varies: it may be a DataTable from whi

11条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-07 19:35

    static string ToCsv(IEnumerable things, Func toStringMethod)
    {
        StringBuilder sb = new StringBuilder();
    
        foreach (T thing in things)
            sb.Append(toStringMethod(thing)).Append(',');
    
        return sb.ToString(0, sb.Length - 1); //remove trailing ,
    }
    

    Use like this:

    DataTable dt = ...; //datatable with some data
    Console.WriteLine(ToCsv(dt.Rows, row => row["ColName"]));
    

    or:

    List customers = ...; //assume Customer has a Name property
    Console.WriteLine(ToCsv(customers, c => c.Name));
    

    I don't have a compiler to hand but in theory it should work. And as everyone knows, in theory, practice and theory are the same. In practice, they're not.

提交回复
热议问题