Posts Tagged ‘SortedList’

Create a delimited list of SortedList Keys in C#

I love C#, but miss the simplicity of PHP sometimes.  Specifically when dealing with collections.  Recently I ran into a situation where PHP’s implode would have been perfect, but I wasn’t able to find any quick and easy built in solution.

I would like to be able to do this

string id_list = implode( ",", mySortedList.Keys );

I’m not aware of any built in ways to do this, so I wrote the following helper function.

///
/// Pass in a SortedList and this will return a string containing a delimited
/// list of keys separated by delim
///
///

///

/// key1{DELIM}key2{DELIM}keyN
public static string SortedListKeysToDelimList(SortedList sl, string delim)
{
StringBuilder sb_keys = new StringBuilder();

foreach (DictionaryEntry dl in sl)
{
sb_keys.Append( dl.Key.ToString() );

// append DELIM only if we're NOT on the last entry
if (dl.Key != sl.GetKey(sl.Keys.Count - 1))
{
sb_keys.Append( delim );
}
}

return sb_keys.ToString();
}

If there is any better way to do this, please leave me a comment.