简体   繁体   中英

Join StringCollection with commas

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?

可以先将 StringCollection 转换为 List 集合: https ://stackoverflow.com/a/844420/4682228。

var commaSeparatedList = string.Join(", ", stringCollection.Cast<string>());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM