我想对HashSet<string>
的元素进行排序,并通过;
字符加入它们。
Python解释器版本:
>>> st = {'jhg', 'uywer', 'nbcm', 'utr'}
>>> strng = ';'.join(sorted(s))
>>> strng
'ASD;anmbh;ashgg;jhghjg'
我寻求的方法的C#签名:
private string getVersionsSorted(HashSet<string> versions);
我可以不使用Linq来做到这一点,但我真的想更好地学习它。
非常感谢!
答案 0 :(得分:3)
请注意,HashSets是无序的。
String.Join(";", versions.OrderBy(v => v).ToArray());
versions.OrderBy(v => v).Join(";");
///<summary>Appends a list of strings to a StringBuilder, separated by a separator string.</summary>
///<param name="builder">The StringBuilder to append to.</param>
///<param name="strings">The strings to append.</param>
///<param name="separator">A string to append between the strings.</param>
public static StringBuilder AppendJoin(this StringBuilder builder, IEnumerable<string> strings, string separator) {
if (builder == null) throw new ArgumentNullException("builder");
if (strings == null) throw new ArgumentNullException("strings");
if (separator == null) throw new ArgumentNullException("separator");
bool first = true;
foreach (var str in strings) {
if (first)
first = false;
else
builder.Append(separator);
builder.Append(str);
}
return builder;
}
///<summary>Combines a collection of strings into a single string.</summary>
public static string Join(this IEnumerable<string> strings, string separator) { return new StringBuilder().AppendJoin(strings, separator).ToString(); }
versions.OrderBy(v => v).Aggregate(new StringBuilder(),
(v, sb) => sb.Append(sb.Length > 0 ? ";" : "").Append(v)
).ToString();
String.Join(";", versions.OrderBy(v => v));
答案 1 :(得分:3)
如果你可以选择使用.NET 4.0,你可以开始使用SortedSet<T>
类,这会大大简化,因为你只需要在你的集合上调用string.Join
然后
否则,如果您看起来只限于.NET 3.5,请尝试以下操作:
private string GetVersionsSorted(ISet<string> versions)
{
return string.Join(",", versions.OrderBy(s => s).ToArray());
}
(注意:如果你使用的是.NET 4.0,你也可以省去ToArray
的电话,这很方便。)
答案 2 :(得分:2)
HashSet<string> hash = new HashSet<string>(new string[] { "b", "a", "d" });
string output = hash.OrderBy(str => str).Aggregate((a, b) => a + ";" + b);
输出:a; b; d
答案 3 :(得分:0)
var versions = new HashSet<string>(new[] { "jhg", "uywer", "nbcm", "utr" });
var result = string.Join(";", versions.OrderBy(x => x).ToArray());
Console.WriteLine(result);