C# HashSet<string> to single string
I have a HashSet<string>
that is added to periodically. What I want to do is to cast the entire HashSet to a string without doing a foreach loop. Does 开发者_JAVA技巧anybody have an example?
You will loop over the contents, whether you explicitly write one or not.
However, to do it without the explicit writing, and if by "cast" you mean "concatenate", you would write something like this
string output = string.Join("", yourSet); // .NET 4.0
string output = string.Join("", yourSet.ToArray()); // .NET 3.5
If you want a single string that is a concatenation of the values in the HashSet, this should work...
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();
}
}
If you want a single method to get all the hashset's items concatenated, you can create a extension method.
[]'s
[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();
}
}
}
You can use Linq:
hashSet.Aggregate((a,b)=>a+" "+b)
which inserts a white space between two elements of your hashset
精彩评论