将Python 3.x片段转换为C#/ LINQ

时间:2010-04-26 20:30:25

标签: c# linq .net-3.5 python-3.x

我想对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来做到这一点,但我真的想更好地学习它。

非常感谢!

4 个答案:

答案 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();

.Net 4.0最快版本:

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);