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