Helen Toomik
Helen Toomik

Reputation: 2115

Join collection of objects into comma-separated string

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 which we need a certain column, or a List<Customer>, etc.

Now we loop through the collection and use string concatenation, for example:

string text = "";
string separator = "";
foreach (DataRow row in table.Rows)
{
    text += separator + row["title"];
    separator = ", ";
}

Is there a better pattern for this? Ideally I would like an approach we could reuse by just sending in a function to get the right field/property/column from each object.

Upvotes: 30

Views: 63289

Answers (11)

Sapan Ghafuri
Sapan Ghafuri

Reputation: 555

For collections you can use this method as well, for example:

string.Join(", ", contactsCollection.Select(i => i.FirstName));

You can select any property that you want to separate.

Upvotes: 2

Umang Patel
Umang Patel

Reputation: 111

I found string.Join and lambda Select<Func<>> helps to write minimum code.

List<string> fruits = new List<string>();
fruits.Add("Mango");
fruits.Add("Banana");
fruits.Add("Papaya");

string commaSepFruits = string.Join(",", fruits.Select(f => "'" + f + "'"));
Console.WriteLine(commaSepFruits);

List<int> ids = new List<int>();
ids.Add(1001);
ids.Add(1002);
ids.Add(1003);

string commaSepIds = string.Join(",", ids);
Console.WriteLine(commaSepIds);

List<Customer> customers = new List<Customer>();
customers.Add(new Customer { Id = 10001, Name = "John" });
customers.Add(new Customer { Id = 10002, Name = "Robert" });
customers.Add(new Customer { Id = 10002, Name = "Ryan" });

string commaSepCustIds = string.Join(", ", customers.Select(cust => cust.Id));
string commaSepCustNames = string.Join(", ", customers.Select(cust => "'" + cust.Name + "'"));

Console.WriteLine(commaSepCustIds);
Console.WriteLine(commaSepCustNames);

Console.ReadLine();

Upvotes: 11

BigBlondeViking
BigBlondeViking

Reputation: 3963

I love Matt Howells answer in this post:

I had to make it into an extension:

public static string ToCsv<T>(this IEnumerable<T> things, Func<T, string> toStringMethod)

Usage (I am getting all the emails and turning them into a CSV string for emails):

var list = Session.Find("from User u where u.IsActive = true").Cast<User>();

return list.ToCsv(i => i.Email);

Upvotes: 2

Mendelt
Mendelt

Reputation: 37483

You could write a function that transforms a IEnumerable<string> 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.

Upvotes: 6

Hosam Aly
Hosam Aly

Reputation: 42453

// 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');
}

Upvotes: 10

leppie
leppie

Reputation: 117250

string.Join(", ", Array.ConvertAll(somelist.ToArray(), i => i.ToString()))

Upvotes: 98

toddmo
toddmo

Reputation: 22416

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"]));

Upvotes: 0

Reputation:

string strTest = "1,2,4,6";
string[] Nums = strTest.Split(',');
Console.Write(Nums.Aggregate<string>((first, second) => first + "," + second));
//OUTPUT:
//1,2,4,6

Upvotes: 1

Ian Mercer
Ian Mercer

Reputation: 39277

In .NET 4 you can just do string.Join(", ", table.Rows.Select(r => r["title"]))

Upvotes: 8

Matt Howells
Matt Howells

Reputation: 41266

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.

Upvotes: 12

Galwegian
Galwegian

Reputation: 42237

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.

Upvotes: 2

Related Questions