これらはどちらも、「:」の区切り文字を使用することを決定し、エスケープ文字を使用して、区切り文字で何か他のことを意味する場合に明確にすることで機能します。したがって、区切り文字を間に挟んで連結する前に、すべての文字列をエスケープする必要があります。これにより、コレクションごとに一意の文字列が得られます。コレクションを同じにしたい場合や順序に関係なく行う必要があるのは、何かを行う前にコレクションをソートすることだけです。私のサンプルはLINQを使用しているため、コレクションが実装されていることを前提IEnumerable<string>
としており、using宣言があることを追加する必要がありますSystem.LINQ
次のように関数にまとめることができます
string GetUniqueString(IEnumerable<string> Collection, bool OrderMatters = true, string Escape = "/", string Separator = ":")
{
if(Escape == Separator)
throw new Exception("Escape character should never equal separator character because it fails in the case of empty strings");
if(!OrderMatters)
Collection = Collection.OrderBy(v=>v);//Sorting fixes ordering issues.
return Collection
.Select(v=>v.Replace(Escape, Escape + Escape).Replace(Separator,Escape + Separator))//Escape String
.Aggregate((a,b)=>a+Separator+b);
}