Dofactory.com
Dofactory.com
 Back to list
Views:   13K
Replies:  1
Archived

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

 
Walt Lynton, Mar 19, 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.
Jun 17, 2010
Yes, it is good one to use
Apr 27, 2010
Really a good one! I will add this to my Extensions library.
Mar 19, 2010
Reply 1
You can already do that with linq.
var commas = users.Aggregate((result, user) => result + "," + user); 

 
Taliesin Sisson, Mar 23, 2010
Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Cookies       Do Not Sell       Licensing      
Made with    in Austin, Texas.  - vsn 44.0.0
© Data & Object Factory, LLC.