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.

About Eric Fickes

Independent Internet Consultant by day. Skateboarder, Bass player, Husband and Father by night. You can hire me to build internet powered solutions
This entry was posted in .net, C#, php and tagged , , , , . Bookmark the permalink.

4 Responses to Create a delimited list of SortedList Keys in C#

  1. Pete says:

    How’s about different?

    SortedList sl = new SortedList();
    sl.Add(1, “hi”);
    sl.Add(2, “there”);
    sl.Add(3, “everyone”);

    IList il = sl.GetKeyList();
    string str = string.Empty;

    for (int i = 0; i < il.Count; i++)
    {
    str += i == 0 ? il[i].ToString() : string.Format(“,{0}”, il[i].ToString());
    }

  2. Eric says:

    Not a bad idea, but I’d still say use a StringBuilder since you might not know the size of your incoming SortedList.

  3. Pete says:

    Last one, promise! :)

    How about this in SortedListKeysToDelimList?

    string[] sa = new string[sl.Keys.Count];
    sl.Keys.CopyTo(sa, 0);
    return string.Join(delim, sa);

  4. Eric says:

    That one is great for a SortedList with keys that are strings. You’d have to manage casting if you have a SortedList with anything but string keys.

    Thanks Pete!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>