c# HashSet< string>到单个字符串
本文关键字:单个 字符串 string HashSet | 更新日期: 2023-09-27 18:02:37
我有一个定期添加的HashSet<string>
。我想做的是将整个HashSet强制转换为字符串,而不需要foreach循环。有人能举个例子吗?
无论是否明确写入,都将遍历内容。
但是,要在没有显式书写的情况下完成它,并且如果"cast"指的是"concatenate",则可以这样写
string output = string.Join("", yourSet); // .NET 4.0
string output = string.Join("", yourSet.ToArray()); // .NET 3.5
如果你想要一个单独的字符串,它是HashSet中的值的连接,这应该工作…
class Program
{
static void Main(string[] args)
{
var set = new HashSet<string>();
set.Add("one");
set.Add("two");
set.Add("three");
var count = string.Join(", ", set);
Console.WriteLine(count);
Console.ReadKey();
}
}
如果您想要一个方法来连接所有的哈希集项,您可以创建一个扩展方法。
[]的
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
HashSet<string> hashset = new HashSet<string>();
hashset.Add("AAA");
hashset.Add("BBB");
hashset.Add("CCC");
Assert.AreEqual<string>("AAABBBCCC", hashset.AllToString());
}
}
public static class HashSetExtensions
{
public static string AllToString(this HashSet<string> hashset)
{
lock (hashset)
{
StringBuilder sb = new StringBuilder();
foreach (var item in hashset)
sb.Append(item);
return sb.ToString();
}
}
}
您可以使用Linq:
hashSet.Aggregate((a,b)=>a+" "+b)
在hashset的两个元素之间插入空白