Home  /  Questions  /  Gem



203   96.8
Mar 19, 2010


Nice Gem! Building comma-separated string from IEnumerable

Here is a nice Gem.  This extension method will allow you to easily build a comma-separated string from an Enumerable list. For example, if you have a list of Customer objects and you need a comma-separated string of all CustomerIds, you just call the CommaSeparate extension method on the list.

Internally we use it a lot to build SQL statements such as

SELECT * FROM User WHERE UserId IN ( comma-separated list )
Here is the code (short and sweet): 

// Comma separate an enumerable source
public static string CommaSeparate<T, U>(this IEnumerable<T> source, Func<T, U> func)
{
    return string.Join(",", source.Select(s => func(s).ToString()).ToArray());
}

And, here is an example of how you'd use it on a list of Users. 
public class User
{
     public int? UserId { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
}


public void Test()
{
    List<User> users = new List<User>
    {
        new User{ UserId = 1, FirstName = "Joe", LastName = "Paterno"},
        new User{ UserId = 2, FirstName = "David", LastName = "VanderHorst" },
        new User{ UserId = 3, FirstName = "Mary", LastName = "McDugal" }
    };

    // This generates commas = "1,2,3"
    string commas = users.CommaSeparate( u => u.UserId );
}

 
 3 comments
 
Really a good one! I will add this to my Extensions library. --- Juan Perez  Mar 19, 2010
 
Yes, it is good one to use --- Srihari Chinna  Apr 27, 2010
 
That was great! Just in need of that, need to save search tags of media user uploads on image server. User uses the same tags to search. Needed to save the in comma separated format. Thanks. --- Jaspalsinh Chauhan  Jun 17, 2010



90   96.5
Mar 23, 2010
You can already do that with linq.
var commas = users.Aggregate((result, user) => result + "," + user); 

 
 1 comment
 
Even better! I was not aware of the Aggregate LINQ extension method. Extra points for you. --- Walt Lynton  Mar 23, 2010