Join collection of objects into comma-separated string

前端 未结 11 1248
无人共我
无人共我 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<T>(IEnumerable<T> things, Func<T, string> 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<Customer> 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.

    0 讨论(0)
  • 2020-12-07 19:35

    As an aside: The first modification I would make is to use the StringBuilder Class instead of just a String - it'll save resources for you.

    0 讨论(0)
  • 2020-12-07 19:36
    string.Join(", ", Array.ConvertAll(somelist.ToArray(), i => i.ToString()))
    
    0 讨论(0)
  • 2020-12-07 19:40
    // using System.Collections;
    // using System.Collections.Generic;
    // using System.Linq
    
    public delegate string Indexer<T>(T obj);
    
    public static string concatenate<T>(IEnumerable<T> collection, Indexer<T> indexer, char separator)
    {
        StringBuilder sb = new StringBuilder();
        foreach (T t in collection) sb.Append(indexer(t)).Append(separator);
        return sb.Remove(sb.Length - 1, 1).ToString();
    }
    
    // version for non-generic collections
    public static string concatenate<T>(IEnumerable collection, Indexer<T> indexer, char separator)
    {
        StringBuilder sb = new StringBuilder();
        foreach (object t in collection) sb.Append(indexer((T)t)).Append(separator);
        return sb.Remove(sb.Length - 1, 1).ToString();
    }
    
    // example 1: simple int list
    string getAllInts(IEnumerable<int> listOfInts)
    {
        return concatenate<int>(listOfInts, Convert.ToString, ',');
    }
    
    // example 2: DataTable.Rows
    string getTitle(DataRow row) { return row["title"].ToString(); }
    string getAllTitles(DataTable table)
    {
        return concatenate<DataRow>(table.Rows, getTitle, '\n');
    }
    
    // example 3: DataTable.Rows without Indexer function
    string getAllTitles(DataTable table)
    {
        return concatenate<DataRow>(table.Rows, r => r["title"].ToString(), '\n');
    }
    
    0 讨论(0)
  • 2020-12-07 19:42

    Here's my favorite answer adapted to the question, and corrected Convert to ConvertAll:

    string text = string.Join(", ", Array.ConvertAll(table.Rows.ToArray(), i => i["title"]));
    
    0 讨论(0)
  • 2020-12-07 19:43

    You could write a function that transforms a IEnumerable into a comma separated string

    public string Concat(IEnumerable<string> stringList)
    {
        StringBuilder textBuilder = new StringBuilder();
        string separator = String.Empty;
        foreach(string item in stringList)
        {
            textBuilder.Append(separator);
            textBuilder.Append(item);
            separator = ", ";
        }
        return textBuilder.ToString();
    }
    

    You can then use Linq to query your collection/dataset/etc to provide the stringList.

    0 讨论(0)
提交回复
热议问题