C# Convert Collection to Delimited String using Linq

Several times I have had the need to take a collection and convert it to a delimited string for displaying in the UI.  I have been using the code below that I found on a blog that I have since lost the link to. However, while at the SEVDNUG meeting tonight Rob showed me an easier way to get the same output using LINQ.

Original Code:

public class CollectionUtilities 
{ 
    public string Join<T>(string delimiter, IEnumerable<T> items, Converter<T, string> converter) 
    { 
        StringBuilder builder = new StringBuilder(); 
        foreach (T item in items) 
        { 
            string converted = converter(item); 
            if (string.IsNullOrEmpty(converted) == false) 
            { 
                builder.Append(converted); 
                builder.Append(delimiter); 
            } 
        } 
        if (builder.Length > 0) 
        {
            builder.Length = builder.Length - delimiter.Length; 
        }

        return builder.ToString(); 
    } 
}
 

New Code:

public class CollectionUtilities 
{ 
    public string Join<T>(string delimiter, IEnumerable<T> items, Converter<T, string> converter) 
    { 
          return string.Join(delimiter, (items.Where(i => string.IsNullOrEmpty(converter(i)) == false).Select(i => converter(i))).ToArray()); 
    } 
}

NUnit Test:

[Test] 
public void JoinTest() 
{ 

    string[] joins = new string[]{"1", "2", "3", "4"}; 
    string joinTest = new.Join(",", joins, item => item); 
    Assert.AreEqual("1,2,3,4", joinTest); 

    joins = new string[] { "1", "", "3", "4" }; 
    joinTest = new CollectionUtilities().Join(",", joins, item => item); 
    Assert.AreEqual("1,3,4", joinTest);

    joins = new string[] { "1"}; 
    joinTest = new CollectionUtilities().Join(",", joins, item => item); 
    Assert.AreEqual("1", joinTest);  
}

Related posts

Comments

June 30. 2008 02:12 AM

Saul

Hey Justin,
I was watching when you and Rob were trying to figure this out. From your solution posted here, it appears to me that while your code is MUCH simpler, it may actually be worse performing. Now, I'm not sure about this, but I wanted to start the discussion (as I'm still new to linq): Since you have the syntax seperated like this, does it take 2 traversals to get the same job that was done in one? Now, granted there is no theoretical difference between an O(n) operation and O(2n), but still seems like a waste of CPU cycles to me...

Saul

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

November 21. 2008 10:23 PM