0

Usually, joining a List with commas is easy using string.Join(). However, coming across a StringCollection today, string.Join() outputs "System.Collections.Specialized.StringCollection" output instead of a comma-separated string.

    [TestMethod]
    public void TestJoin()
    {
        StringCollection stringCollection = new StringCollection() { "Denis", "Jason", "Shawn" };
        // Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException:
        // 'Assert.AreEqual failed. Expected:<Denis, Jason, Shawn>. Actual:<System.Collections.Specialized.StringCollection>.'
        Assert.AreEqual("Denis, Jason, Shawn", string.Join(", ", stringCollection));
    }

How do we Join() a StringCollection?

Denis G. Labrecque
  • 1,023
  • 13
  • 29
  • 1
    This is not quite correct. if sc is a StringCollection object, string.Join(", ", sc) will call `ToString` on this object which yields "System.Collections.Specialized.StringCollection" (because ToString is not overridden in StringCollection). Therefore the result of string.Join will be the string "System.Collections.Specialized.StringCollection" – Klaus Gütter Jun 17 '22 at 14:59
  • 1
    `string.Join() creates a StringCollection output` no it doesn't. It always returns a `string`. Post your code. You're probably not calling the method you think you are – Panagiotis Kanavos Jun 17 '22 at 15:01
  • @PanagiotisKanavos Klaus' deduction is correct. See the quick unit test I hadn't bothered to post. – Denis G. Labrecque Jun 17 '22 at 15:15

1 Answers1

4

It is possible to convert the StringCollection to a List collection first: https://stackoverflow.com/a/844420/4682228.

var commaSeparatedList = string.Join(", ", stringCollection.Cast<string>());
Denis G. Labrecque
  • 1,023
  • 13
  • 29
  • 3
    You don't need the `ToList` since `string.Join` has an overload that takes `IEnumerable` – juharr Jun 17 '22 at 14:55
  • 2
    To expand on this answer: The reason you need to write `.Cast()` is because `string.Join()` is expecting an `IEnumerable`, not a plain `IEnumerable`. The `.Cast()` converts an `IEnumerable` to an `IEnumerable`. That is the specific job of [`IEnumerable.Cast()`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.cast?view=net-6.0) – Matthew Watson Jun 17 '22 at 15:11